参考链接
Python for循环写入文件--小结-dsy851009-ChinaUnix博客
二进制文件的读写-python3_尘埃落定-优快云博客_python3 读取二进制文件
https://huiqinbo.iteye.com/blog/2192888
这两天需要用python写文件。总结如下:
Python如何让读取文件内容为字符串 ?案例详解
Python如何让读取文件内容为字符串 ?案例详解 - 程序员的人生A - 博客园
https://www.jb51.net/article/143647.htm
#写在原文件中
fp3=open("file3.txt","r+") #不用w w会清空数据
s=fp3.read()#读出
fp3.seek(0,0) #指针移到头 原来的数据还在是替换 会存在一个问题 如果少 会替换不了全部数据,自已思考解决!
#从头写入
fp3.write(s.replace("hello","good"))
fp3.close()
python删除文件指定行_迷风小白-优快云博客_python删除txt指定行
import os
lines = (i for i in open('test.txt', 'r') if 'pig' not in i )
f = open('test_new.txt', 'w', encoding="utf-8")
f.writelines(lines)
f.close()
os.rename('test.txt', 'test.bak')
os.rename('test_new.txt', 'test.txt')
os.remove('test.bak')
用python实现文件读取和内容替换 - 矮油~ - 博客园
注意,调用writelines写入多行在性能上会比使用write一次性写入要高。
推荐使用此种方式,但是with之后,会自动关闭f。
with open('test.dat', 'wb') as f:
print("open test.dat")
f.write(mydata)
如果想要循环写入的话
with open("wow_list_dong", "w") as f:
for a in channels_massage:
b = a[1] + " " + a[2] + " " + a[3]
b += "\n"
f.write(b)
但是有些时候,我们不会同时在一个函数里执行此操作。
global count
count = 0
try:
f = open('test.dat', 'wb')
print("open test.dat")
except FileNotFoundError as e:
print('指定的文件无法打开')
except IOError as e:
print('读写文件时出现错误.')
print('程序执行结束.')
def write_file(f, data):
try:
f.write(data)
except FileNotFoundError as e:
print('指定的文件无法打开')
except IOError as e:
print('读写文件时出现错误.')
print('程序执行结束.')
f.close()
def func_called(mydata, num):
# print("print by python,called by cpp!")
global count
count+=1
print("print by python: %s, count: %d" %(str(len(mydata)), count))
print("the length of %d: %s" %(num, mydata))
list_data.append(mydata)
write_file(f, mydata)
if count == 10:
count = 0
f.flush()
print("flush test.dat count: %d" %(count))
print("write_file test.dat")
这里注意global count全局变量的使用注意