[英]Remove element from multiple files with python
我有下一个脚本,它可以删除文件夹中多个文件中的逗号。 可以,但是我想“改善”。 在某个时候,我必须将整个文件存储在内存中,然后将其写入。 我尝试使用逐行读取和写入的readlines,但在最好的情况下,我最终得到的结果是a的第一部分和原来的一样,第二部分的文件删除了逗号。
import os
os.chdir(raw_input("Folder with files to remove \" (comma): "))
for files in os.listdir(os.getcwd()):
f = open(files, "r")
rep = f.read().replace('"','')
f.close()
f = open(files, "w")
f.write(rep)
f.close()
这是一个演示文件
"GO:0016925" 0.613185459363216
"GO:0007029" 0.617740206445514
"GO:0006310" 0.617740206445514
使用一个临时文件:
from tempfile import mkstemp
from shutil import move
import os
os.chdir(raw_input("Folder with files to remove \" (comma): "))
for files in os.listdir(os.getcwd()):
#create temp file
f, p = mkstemp()
#do the copy with the replace
with open(p,'w') as new:
with open(files) as old:
for line in old:
new.write(line.replace(('"','')))
os.close(f)
#replace the old file by the new one
os.remove(files)
move(p, files)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.