Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - writing back into the same file after reading from the file

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()+"
")

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()+"
")

      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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...