python文件的使用_Python文件操作

使用文件的目的:

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

文件操作流程:

打开文件,或者新建立一个文件

读/写数据

关闭文件

一. 打开文件

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

open(文件名,访问模式)

1 f=open(filepath,mode)

1135071-20170530083422336-736734134.png

二. 操作文件

写数据

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 incontent: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()

制作文件备份代码

ContractedBlock.gif

ExpandedBlockStart.gif

1 #coding=utf-8

2

3 oldFileName = input("请输入要拷贝的文件名字:")4

5 oldFile = open(oldFileName,'r')6

7 #如果打开文件

8 ifoldFile:9

10 #提取文件的后缀

11 fileFlagNum = oldFileName.rfind('.')12 if fileFlagNum >0:13 fileFlag =oldFileName[fileFlagNum:]14

15 #组织新的文件名字

16 newFileName = oldFileName[:fileFlagNum] + '[复件]' +fileFlag17

18 #创建新文件

19 newFile = open(newFileName, 'w')20

21 #把旧文件中的数据,一行一行的进行复制到新文件中

22 for lineContent inoldFile.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 "读取的数据是 :", str5

6 #查找当前位置

7 position =f.tell()8 print "当前文件位置 :", position9

10 str = f.read(3)11 print "读取的数据是 :", str12

13 #查找当前位置

14 position =f.tell()15 print "当前文件位置 :", position16

17 f.close()

文件定位

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

seek(offset, from)有2个参数

offset:偏移量

from:方向

0:表示文件开头

1:表示当前位置

2:表示文件末尾

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

ContractedBlock.gif

ExpandedBlockStart.gif

1 #打开一个已经存在的文件

2 f = open("test.txt", "r")3 str = f.read(30)4 print "读取的数据是 :", str5

6 #查找当前位置

7 position =f.tell()8 print "当前文件位置 :", position9

10 #重新设置位置

11 f.seek(5,0)12

13 #查找当前位置

14 position =f.tell()15 print "当前文件位置 :", position16

17 f.close()

View Code

离文件末尾,3字节处

1 #打开一个已经存在的文件

2 f = open("test.txt", "r")3

4 #查找当前位置

5 position =f.tell()6 print "当前文件位置 :", position7

8 #重新设置位置

9 f.seek(-3,2)10

11 #读取到的数据为:文件最后3个字节数据

12 str =f.read()13 print "读取的数据是 :", str14

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()进行文件重命名。

ContractedBlock.gif

ExpandedBlockStart.gif

1 #coding=utf-8

2

3 #批量在文件名前加前缀

4

5 importos6

7 funFlag = 1 #1表示添加标志 2表示删除标志

8

9 folderName = './renameDir/'

10

11 #获取指定路径的所有文件名字

12 dirList =os.listdir(folderName)13

14 #遍历输出所有文件名字

15 for name indirList:16 printname17

18 if funFlag == 1:19 newName = '[东哥出品]-' +name20 elif funFlag == 2:21 num = len('[东哥出品]-')22 newName =name[num:]23 printnewName24

25 os.rename(folderName+name, folderName+newName)

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

1 #!/usr/bin/env python

2 #!coding:utf-8

3 #Author:Liuxiaoyang

4

5

6 deflogin(username,password):7 flag=08 with open('user.txt','r') as f:9 lines=f.readlines()10 for line inlines: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 returnFalse20 else:21 returnTrue22

23 defmenu():24 whileTrue: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 defbrowse():53 with open('info.txt','r') as f:54 lines=f.readlines()55 for line inlines:56 print(line.strip())57

58 deffind_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 inlines: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 deffind_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 inlines: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 defdelete_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 inlines: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 defupdate():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 inlines: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 defadd_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 defquit():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|admin2 user|user

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值