writing back into the same file after reading from the file

前端 未结 2 1817
清歌不尽
清歌不尽 2020-12-19 03:54

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(         


        
2条回答
  •  情话喂你
    2020-12-19 04:14

    The problem with your approach is that you need both an input stream and an output stream, which can point at different places in the same file. If you want to use f.seek() then you will need to store the position using f.tell() after each read and write. For example:

    f = open(filename, 'r+')
    while True:
        i = f.readline()
        if i == '': break
        in = f.tell()
        f.seek(out)
        f.write(i.rstrip()+"\n")
        out = f.tell()
        f.seek(in)
    

    But that's confusing and prone to errors. If the file isn't too big, why not read it all into memory and then write it back out again?

    in = open(filename, 'r')
    lines = in.read()
    in.close()
    out = open(filename, 'w')
    out.write([line.rstrip()+'\n' for line in lines.split('\n')])
    out.close()
    

    If the file is too large to fit into memory, then write the lines to a temporary file and then rename the file when you are done:

    out = open(filename+'.tmp', 'w')
    with open(filename, 'r') as f:
        for i in f:
            out.write(i.rstrip()+"\n")
    out.close()
    os.rename(filename+'.tmp', filename)
    

提交回复
热议问题