从文件中读取后写回同一个文件 [英] writing back into the same file after reading from the file
问题描述
with open(filename,'r +')as f:
for i in f:
f.write(i.rstrip()+\\\
)
这似乎写在文件的末尾,保持原始数据完整的文件。我知道使用 f.seek(0)
会把指针移回到文件的开始位置,我假设这个解决方案是需要的。
你能否告诉我这是否有不同的方法,或者我在正确的补丁中只需要添加更多的逻辑代码?
使用临时文件。 Python提供了以安全的方式创建临时文件的功能。调用下面的例子:python modify.py target_filename
import tempfile
import sys
def modify_file(filename):
#创建临时文件读/写
t = tempfile.NamedTemporaryFile(mode =r +)
#Open input file read-只有
i = open(filename,'r')
#将输入文件复制到临时文件,修改为
为i中的行
t.write (line.rstrip()+\\\
)
i.close()#关闭输入文件
t.seek(0)#将临时文件重新开始
o = open(文件名,w)#Reopen输入文件可写
#使用临时文件内容创建原始文件
为t中的行
o.write(line)
t.close()#关闭临时文件,将导致它被删除
if __name__ ==__main__:
modify_file(sys.argv [1])$ b $ b
R这里引用:
http://docs.python.org/2/library/ tempfile.html
My aim is to read line from the file , strip the blank spaces at the end of it and write back into the same file. I have tried the following code:
with open(filename, 'r+') as f:
for i in f:
f.write(i.rstrip()+"\n")
This seems to write at the end of the file, keeping initial data in the file intact . I know that using f.seek(0)
would take the pointer back to start of the file , which I am assuming would be somehow required for this solution.
Can you please advise if there is different approach for this or am I on the right patch just need to add more logic into the code?
Use a temporary file. Python provides facilities for creating temporary files in a secure manner. Call example below with: python modify.py target_filename
import tempfile
import sys
def modify_file(filename):
#Create temporary file read/write
t = tempfile.NamedTemporaryFile(mode="r+")
#Open input file read-only
i = open(filename, 'r')
#Copy input file to temporary file, modifying as we go
for line in i:
t.write(line.rstrip()+"\n")
i.close() #Close input file
t.seek(0) #Rewind temporary file to beginning
o = open(filename, "w") #Reopen input file writable
#Overwriting original file with temporary file contents
for line in t:
o.write(line)
t.close() #Close temporary file, will cause it to be deleted
if __name__ == "__main__":
modify_file(sys.argv[1])
References here: http://docs.python.org/2/library/tempfile.html
这篇关于从文件中读取后写回同一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!