码迷,mamicode.com
首页 > 编程语言 > 详细

Python文件操作

时间:2017-05-30 13:02:48      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:while   opened   重命名   offset   search   com   操作文件   test   port   

使用文件的目的:

就是把一些存储存放起来,可以让程序下一次执行的时候直接使用,而不必重新制作一份,省时省力

 

文件操作流程:

  1. 打开文件,或者新建立一个文件
  2. 读/写数据
  3. 关闭文件

 

一. 打开文件

在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件

open(文件名,访问模式)

1 f=open(filepath,mode)

技术分享

 

二. 操作文件

写数据

1 f = open(test.txt, w)
2 f.write(hello world, i am here!)
3 f.close()

如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

 

读数据

使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据

1 f = open(test.txt, r)
2 content = f.read(5)
3 print(content)
4 print("-"*30)
5 content = f.read()
6 print(content)
7 f.close()

 

就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

1 #coding=utf-8
2 f = open(test.txt, r)
3 content = f.readlines()
4 print(type(content))
5 i=1
6 for temp in content:
7     print("%d:%s"%(i, temp))
8     i+=1
9 f.close()

 

1 #coding=utf-8
2 
3 f = open(test.txt, r)
4 content = f.readline()
5 print("1:%s"%content)
6 content = f.readline()
7 print("2:%s"%content)
8 f.close()

三. 关闭文件

1 # 新建一个文件,文件名为:test.txt
2 f = open(test.txt, w)
3 # 关闭这个文件
4 f.close()

 

 制作文件备份代码

技术分享
 1 #coding=utf-8
 2 
 3 oldFileName = input("请输入要拷贝的文件名字:")
 4 
 5 oldFile = open(oldFileName,r)
 6 
 7 # 如果打开文件
 8 if oldFile:
 9 
10     # 提取文件的后缀
11     fileFlagNum = oldFileName.rfind(.)
12     if fileFlagNum > 0:
13         fileFlag = oldFileName[fileFlagNum:]
14 
15     # 组织新的文件名字
16     newFileName = oldFileName[:fileFlagNum] + [复件] + fileFlag
17 
18     # 创建新文件
19     newFile = open(newFileName, w)
20 
21     # 把旧文件中的数据,一行一行的进行复制到新文件中
22     for lineContent in oldFile.readlines():
23         newFile.write(lineContent)
24 
25     # 关闭文件
26     oldFile.close()
27     newFile.close()
View Code

 

文件定位读写

在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取

 1  # 打开一个已经存在的文件
 2     f = open("test.txt", "r")
 3     str = f.read(3)
 4     print "读取的数据是 : ", str
 5 
 6     # 查找当前位置
 7     position = f.tell()
 8     print "当前文件位置 : ", position
 9 
10     str = f.read(3)
11     print "读取的数据是 : ", str
12 
13     # 查找当前位置
14     position = f.tell()
15     print "当前文件位置 : ", position
16 
17     f.close()

文件定位

如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()

seek(offset, from)有2个参数

  • offset:偏移量
  • from:方向

0:表示文件开头

1:表示当前位置

2:表示文件末尾

从文件开头,偏移5个字节

技术分享
 1     # 打开一个已经存在的文件
 2     f = open("test.txt", "r")
 3     str = f.read(30)
 4     print "读取的数据是 : ", str
 5 
 6     # 查找当前位置
 7     position = f.tell()
 8     print "当前文件位置 : ", position
 9 
10     # 重新设置位置
11     f.seek(5,0)
12 
13     # 查找当前位置
14     position = f.tell()
15     print "当前文件位置 : ", position
16 
17     f.close()
View Code

离文件末尾,3字节处

 1   # 打开一个已经存在的文件
 2     f = open("test.txt", "r")
 3 
 4     # 查找当前位置
 5     position = f.tell()
 6     print "当前文件位置 : ", position
 7 
 8     # 重新设置位置
 9     f.seek(-3,2)
10 
11     # 读取到的数据为:文件最后3个字节数据
12     str = f.read()
13     print "读取的数据是 : ", str
14 
15     f.close()

 

文件重命名和删除

import os

os.rename(oldFileName,newFileName)

 

import os

os.remove(要删除的文件名)

 

文件夹相关操作

os.getcwd()  获取当前工作目录

os.mkdir()    新建目录

os.rmdir()    删除目录

os.listdir()    返回目录的文件和目录列表

os.chdir()     修改默认目录

 

批量修改文件名

先找到所有的文件 os.listdir(),遍历返回的列表,然后通过os.rename()进行文件重命名。

技术分享
 1      #coding=utf-8
 2 
 3     # 批量在文件名前加前缀
 4 
 5     import os
 6 
 7     funFlag = 1 # 1表示添加标志  2表示删除标志
 8 
 9     folderName = ./renameDir/
10 
11     # 获取指定路径的所有文件名字
12     dirList = os.listdir(folderName)
13 
14     # 遍历输出所有文件名字
15     for name in dirList:
16         print name
17 
18         if funFlag == 1:
19             newName = [东哥出品]- + name
20         elif funFlag == 2:
21             num = len([东哥出品]-)
22             newName = name[num:]
23         print newName
24 
25         os.rename(folderName+name, folderName+newName)
View Code

 

文件版 学生信息管理系统代码如下:

技术分享
  1 #!/usr/bin/env python
  2 #!coding:utf-8
  3 #Author:Liuxiaoyang
  4 
  5 
  6 def login(username,password):
  7     flag=0
  8     with open(user.txt,r) as f:
  9         lines=f.readlines()
 10         for line in lines:
 11             if username==line.split(|)[0].strip() and password==line.split(|)[1].strip():
 12                 flag=1
 13                 print(hello world)
 14                 break
 15             else:
 16                 continue
 17         print(flag)
 18     if flag==0:
 19         return False
 20     else:
 21         return True
 22 
 23 def menu():
 24     while True:
 25         print("-"*50)
 26         print("Welcome to Info System v1.0")
 27         print("-"*50)
 28         print("1. browse(浏览)")
 29         print("2. find by id (通过身份证号查找信息)")
 30         print("3. find by name (通过姓名查找信息)")
 31         print("4. delete by id (通过身份证号删除信息)")
 32         print("5. update info (修改信息)")
 33         print("6. add info (新增信息)")
 34         print("7. quit (退出)")
 35         choice=int(input("Please input your choice: "))
 36         if choice==1:
 37             browse()
 38         if choice==2:
 39             find_by_id()
 40         if choice==3:
 41             find_by_name()
 42         if choice==4:
 43             delete_by_id()
 44         if choice==5:
 45             update()
 46         if choice==6:
 47             add_info()
 48         if choice==7:
 49             quit()
 50 
 51 
 52 def browse():
 53     with open(info.txt,r) as f:
 54         lines=f.readlines()
 55         for line in lines:
 56             print(line.strip())
 57 
 58 def find_by_name():
 59     name_input=input("Please input a name that you want to search : ")
 60     with open(info.txt,r) as f:
 61         lines=f.readlines()
 62         for line in lines:
 63             if line.split(-)[0].strip()==name_input:
 64                 print(**50)
 65                 print(line.strip())
 66                 print(**50)
 67                 break
 68             else:
 69                 continue
 70         else:
 71             print("No Userinfo that you want to search~")
 72 
 73 def find_by_id():
 74     id_input=input("Please input a id that you want to search : ")
 75     with open(info.txt,r) as f:
 76         lines=f.readlines()
 77         for line in lines:
 78             if line.split(-)[1].strip()==id_input:
 79                 print(**50)
 80                 print(line.strip())
 81                 print(**50)
 82                 break
 83             else:
 84                 continue
 85         else:
 86             print("No Userinfo that you want to search~")
 87 
 88 def delete_by_id():
 89     user_id=input("Please input an id that you want to delete : ")
 90     with open(info.txt,r+) as f1:
 91         lines=f1.readlines()
 92         for line in lines:
 93             if line.split(-)[1].strip()==user_id:
 94                 lines.remove(line)
 95     with open(info.txt,w) as f2:
 96         f2.writelines(lines)
 97     print("Delete successfully~")
 98 
 99 def update():
100     user_id=input("Please input an id that you want to update : ")
101     new_user_name=input("Please input a name that you want to update: ")
102     new_user_id=input("Please input an id that you want to upate: ")
103     with open(info.txt,r+) as f1:
104         lines=f1.readlines()
105         for line in lines:
106             if line.split(-)[1].strip()==user_id:
107                 lines.insert(lines.index(line),-.join((new_user_name,new_user_id))+\n)
108                 lines.remove(line)
109     with open(info.txt,w) as f2:
110         f2.writelines(lines)
111     print("Update successfully~")
112 
113 def add_info():
114     user_name=input("Please input your name that you want to add : ").strip()
115     user_id=input("Please input your id that you want to add : ").strip()
116     with open(info.txt,a) as f:
117         f.write(-.join((user_name,user_id))+\n)
118     print(Add new info successfully!)
119 
120 def quit():
121     ensure=input("Are you sure quit this system? y or n    :")
122     if ensure==y:
123         exit()
124     else:
125         menu()
126     
127 if __name__ == __main__:
128     username=input("Please input your username : ").strip()
129     password=input("Please input your password : ").strip()
130     if login(username,password)==True:
131         print("Welcome")
132         menu()
133     else:
134         print("Discard")
View Code

info.txt内容格式

1 liuxiaoyang-24
2 yangyang-26

user.txt内容格式   存储登录用户账号 信息

1 admin|admin
2 user|user

 

Python文件操作

标签:while   opened   重命名   offset   search   com   操作文件   test   port   

原文地址:http://www.cnblogs.com/PythonInMyLife/p/6919669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!