6.2 文本文件操作案例精选

  1 向文本文件中写入内容

 1 s = 'Hello world
文本文件的读取方法
文本文件的写入方法'
 2 #打开文件
 3 #f = open('infomation.txt','w',encoding='utf-8')
 4 #写入文件内容
 5 #f.write(s)
 6 #关闭文件连接
 7 #f.close()
 8 
 9 #========== 把内容写入文件后再从文件中读取内容
10 
11 f = open('infomation.txt','r',encoding='utf-8')
12 print(f.read())
13 f.close()
14 
15 '''
16 Hello world
17 文本文件的读取方法
18 文本文件的写入方法
19 '''

  

  拓展知识:文件操作一般都要遵循“打开文件--读写文件--关闭文件”的标准套路,但是如果文件读写操作代码引发了异常,很难保证文件能够被正常关闭,使用上下文管理关键字with可以避免这个问题。关键字with可以自动管理资源,不论因为什么原因(哪怕是代码引发了异常)跳出with块,总能保证文件被正确关闭,并且可以在代码块执行完毕后自动还原进入该代码块时的现场,常用于文件操作、数据库连接、网络通信连接等场合。有了with,再也不用大新文件没有关闭了。上面的代码改写如下

 1 s = 'Hello world
文本文件的读取方法
文本文件的写入方法'
 2 #打开文件
 3 with open('infomation.txt','w',encoding='utf-8') as f:
 4     #写入文件内容
 5     #f.write(s)
 6     pass
 7 
 8 #这里不需要再显式写文件对象的close()
 9 
10 
11 #另外,上下文管理语句with还支持下面的用法:
12 with open('infomation.txt','w',encoding='utf-8') as fw,open('infomation.txt','r',encoding='utf-8') as fr:
13     fw.write(s)
14     fw.flush()
15     print(fr.read())
16 
17 '''
18 Hello world
19 文本文件的读取方法
20 文本文件的写入方法
21 '''

   

    拓展知识:在交互模式下使用文件对象的write()方法写入文件时,会显示成功写入的字符数量。如果不想显示这个数字,可以先导入sys模块,然后执行语句 sys.stdout=open('null','w'),这样再写入文件时就不会显示写入的字符的数量了。

  拓展知识:JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读的编写,同时也易于机器解析和生成(一般用于提升网络传输速率),是一种比较理想的编码与解码格式。Python标准库json提供对JSON的支持,例如:

 1 import json
 2 
 3 x = [1,2,3]
 4 
 5 #对列表进行编码
 6 a = json.dumps(x)
 7 print(type(a))   #<class 'str'>
 8 
 9 #解码
10 b = json.loads(a)
11 print(type(b))  #<class 'list'>
12 
13 d = {'a':1,'b':2,'c':3}
14 
15 y = json.dumps(d)
16 json.loads(y)
17 
18 #对字典编码并写入文件
19 with open('infomation.txt','w',encoding='utf-8') as fw,open('infomation.txt','r',encoding='utf-8') as fr:
20     json.dump(d,fw)
21     fw.flush()
22     print(fr.read())   #{"b": 2, "c": 3, "a": 1}

  3 读取并显示文本文件的所有行。

 1 with open('infomation.txt','r',encoding='utf-8') as fp:
 2     while True:
 3         line = fp.readline()
 4         if not line:
 5             break
 6         print(line)
 7 
 8 #{"c": 3, "b": 2, "a": 1}
 9 
10 #文件对象也是可以迭代的,
11 
12 with open('infomation.txt','r',encoding='utf-8') as fp:
13     for line in fp:
14         print(line)
15 
16 #{"c": 3, "b": 2, "a": 1}
17 
18 
19 #或者,也可以直接使用文件对象的readlines()方法来实现,但是操作大文件时不建议这样做,因为这会消耗大量的内存资源。
20 
21 with open('infomation.txt','r',encoding='utf-8') as fp:
22     lines = fp.readlines()   #lines是一个列表
23     print(''.join(lines))
24 
25 #{"c": 3, "b": 2, "a": 1}

  4 移动文件指针。文件infomation.txt中内容为Python之禅原文。

 1 fp = open('infomation.txt','r+',encoding='utf8')
 2 print(fp.tell())   #返回文件指针的当前位置  0  说明指针在文件头部
 3 print(fp.read(20))    #从文件中读取20个字符出来    Beautiful is better
 4 
 5 print(fp.seek(13))   #重新定位文件指针的位置   13
 6 #print(fp.read(5))    #重新定位文件指针后,在读取5个字符出来   bette
 7 
 8 print(fp.write('测试'))  #在指针当前位置写入内容,目前指针位置为 18
 9 fp.flush()
10 print(fp.seek(0))   #重新定位文件指针的位置   0
11 print(fp.read(30))  #Beautiful is 测试 than ugly.

  5 假设文件data.txt中有若干整数,整数之间使用英文逗号分隔,编写程序读取所有整行,将其按升序后再写入文本文件 data_asc.txt中。

 1 with open('data.txt','r',encoding='utf-8') as fr,open('data_asc.txt','w',encoding='utf-8') as fw:
 2     data = fr.readline()
 3     #print(data)  #67,88,23,11,8,9,33,94,30,74.70
 4     #print(type(data))   #<class 'str'>
 5     l = data.split(',')
 6     print(l)   #['67', '88', '23', '11', '8', '9', '33', '94', '30', '74', '70']
 7 
 8     #对列表进行升序排序
 9     ll = sorted(l,key=lambda x:int(x))
10     print(ll)    #['8', '9', '11', '23', '30', '33', '67', '70', '74', '88', '94']
11     s = ','.join(ll)
12     print(s)     #8,9,11,23,30,33,67,70,74,88,94
13 
14     #最后把得到的字符串 s 写入到文件 data_asc.txt
15     fw.write(s)

  上述代码是我在data中只写了一行数字,,考虑不周全。下面是作者的代码:

 1 with open('data.txt','r',encoding='utf-8') as fr,open('data_asc.txt','w',encoding='utf-8') as fw:
 2     data = fr.readlines()                      #读取所有行
 3     data = [line.strip() for line in data]     #删除每行两侧的空白字符
 4     data=','.join(data)                        #合并所有的行,把所有的行拼成一个大字符串
 5     data = data.split(',')                     #把大字符串拆分成列表元素
 6     data = [int(item) for item in data]        #将列表元素转换成数字,也可用map()
 7     #data = map(lambda x:int(x),data)
 8     data.sort()                                #对列表中的数字进行升序排序
 9     data = ','.join(map(str,data))             #将结果转换为字符串,列表中要是字符串才能这么用
10     print(data)                                #8,9,11,23,30,33,67,70,74,88,94
11 
12     fw.write(data)                             #将最终结果写入到data_asc.txt文件中

  拓展知识:CSV(Comma Separated Values)格式的文件常用于电子表格和数据库中内容的导入和导出。Python标准库csv提供的reader、writer对象和DictReader和DictWriter类很好地支持了CSV格式文件的读写操作。另外,csvkit支持命令行方式来实现更多关于CSV文件的操作以及与其他文件格式的转换。

 1 #往test.csv文件中写入内容
 2 import csv
 3 with open('test.csv','w',encoding='utf-8',newline='') as fw,open('test.csv','r',encoding='utf-8',newline='') as fr :
 4     test_writer = csv.writer(fw,delimiter=' ',quotechar='"')   #创建writer对象
 5     test_writer.writerow(['red','blue','green'])               #写入一行内容
 6     test_writer.writerow(['test_string'] * 5)
 7     fw.flush()
 8     #文件内容写入完毕后开始从文件中读取内容
 9     #创建reader对象
10     test_reader = csv.reader(fr,delimiter=' ',quotechar='"')
11     #遍历文件中的所有行
12     for row in test_reader:
13         print(row)          #每行作为一个列表返回
14 '''
15 ['red', 'blue', 'green']
16 ['test_string', 'test_string', 'test_string', 'test_string', 'test_string']
17 '''
 1 #往test.csv文件中写入内容
 2 import csv
 3 with open('test.csv','w',encoding='utf-8',newline='') as fw,open('test.csv','r',encoding='utf-8',newline='') as fr :
 4 
 5     test_writer = csv.writer(fw, delimiter=' ', quotechar='"')  # 创建writer对象
 6     test_writer.writerow(['red', 'blue', 'green'])  # 写入一行内容
 7     test_writer.writerow(['test_string'] * 5)
 8     fw.flush()
 9 
10 
11     #创建reader对象,使用 ":" 作为分隔符
12     test_reader = csv.reader(fr,delimiter=':',quotechar='"')
13 
14     for row in test_reader:
15         print(row)          #每行作为一个列表返回
16 '''
17 ['red', 'blue', 'green']
18 ['test_string', 'test_string', 'test_string', 'test_string', 'test_string']
19 '''
 1 #往test.csv文件中写入内容
 2 import csv
 3 with open('test.csv','w',encoding='utf-8',newline='') as fw,open('test.csv','r',encoding='utf-8',newline='') as fr :
 4 
 5     test_writer = csv.writer(fw, delimiter=' ', quotechar='"')  # 创建writer对象
 6     test_writer.writerow(['red', 'blue', 'green'])  # 写入一行内容
 7     test_writer.writerow(['test_string'] * 5)
 8     fw.flush()
 9 
10 
11     #创建reader对象,使用 ":" 作为分隔符
12     test_reader = csv.reader(fr,delimiter=' ',quotechar='"')
13 
14     for row in test_reader:
15         print(','.join(row))          #每行作为一个列表返回
16 '''
17 red,blue,green
18 test_string,test_string,test_string,test_string,test_string
19 '''
 1 #往test.csv文件中写入内容
 2 import csv
 3 with open('test.csv','w',encoding='utf-8',newline='') as fw,open('test.csv','r',encoding='utf-8',newline='') as fr :
 4 
 5     #在csv中定义两列,并写入数据
 6     hearders = ['姓氏','名字']
 7     test_dictWriter = csv.DictWriter(fw,fieldnames=hearders)     #创建DictWriter对象
 8     test_dictWriter.writeheader()                               #写入表头信息
 9 
10     #开始往文件里写内容
11     test_dictWriter.writerow({'姓氏':'','名字':''})
12     test_dictWriter.writerow({'姓氏': '', '名字': ''})
13     test_dictWriter.writerow({'姓氏': '', '名字': ''})
14 
15     fw.flush()
16 
17     #读取文件内容
18     test_dictReader = csv.DictReader(fr)        #创建DictRearder对象
19     print(','.join(test_dictReader.fieldnames)) #读取表头信息
20     for row in test_dictReader:
21         print(row['姓氏'],',',row['名字'])
22         
23 '''
24 姓氏,名字
25 张 , 三
26 李 , 四
27 王 , 五
28 '''

  6 编写程序,保存为demo.py,运行后生成文件demo_new.py,其中的内容与demo.py一致,但是在每行的行尾加上了行号。

 1 filename = 'demo.py'
 2 
 3 with open(filename,'r',encoding='utf-8') as fp:
 4     lines = fp.readlines()          #读取所有行
 5 
 6 #获取最长的行的长度
 7 maxLength = max(map(len,lines))
 8 print(maxLength)
 9 
10 #遍历所有行
11 for index,line in enumerate(lines):
12     newLine = line.rstrip()            #删除每行右侧的空白字符
13     newLine = newLine + ' ' * (maxLength - len(newLine))   #在每行右侧填充空格
14     newLine = newLine + '#' + str(index + 1) + '
'            #在每行右侧增加行号
15     lines[index] = newLine                                     #把新组装的行放到列表中
16 
17 #把新组装的列中写入到demo_new.py文件中
18 with open('demo_new.py','w',encoding='UTF-8') as fp:
19     fp.writelines(lines)

  7 计算文本文件中最长行的长度和该行的内容

1 with open('infomation.txt') as fp:
2     result = [0,'']
3     for line in fp:
4         t = len(line)
5         if t > result[0]:
6             result = [t,line]
7             
8 print(result)
原文地址:https://www.cnblogs.com/avention/p/8760982.html