今日总结
报错:ValueError: I/O operation on closed file.
原因为代码结构上提示行未正确缩进,导致程序尝试修改已经关闭的文件,在用with语句时要注意此问题。代码中倒数第三行若没有缩进与倒数第二行平齐就会出现此问题。
def exchange(f_name):
list3=[]
with open(f_name,mode="r",encoding="UTF-8") as f1,\
open(f_name+"_副本",mode="w",encoding="UTF-8") as f2:
for line2 in f1.readlines():
list3.append(line2)
seq=["%nprocshared=28\n","%mem=40GB\n" "%chk=c3v.chk\n","#p sp b3lyp/6-31g(d)" ,"c3v"]
f2.writelines(seq)
f2.writelines(list3[4:])
os.remove(f_name)
os.rename(f_name+"_副本",f_name)
'''
词条:line = line.strip()
strip可以使读取列表时去除str的首尾空行,也会去除\n这样的换行符号
|