python写⽂件以及全局变量int类型的使⽤注意参考链接
这两天需要⽤python写⽂件。总结如下:
#写在原⽂件中
fp3=open("","r+") #不⽤w w会清空数据
ad()#读出
fp3.seek(0,0) #指针移到头原来的数据还在是替换会存在⼀个问题如果少会替换不了全部数据,⾃已思考解决!
#从头写⼊
fp3.place("hello","good"))
fp3.close()
import os
lines = (i for i in open('', 'r') if 'pig' not in i )
f = open('', 'w', encoding="utf-8")
f.writelines(lines)
f.close()
注意,调⽤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('程序执⾏结束.')writelines使用方法python
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全局变量的使⽤注意
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论