Search code examples
pythonpython-3.xlistfwrite

Concenating to every value in a list


So I have a file with some lines of text:

here's a sentence
look! another one
here's a third one too
and another one
one more

and I have some code that takes the each line and puts it into a list and then reverses the order of the whole list but now I don't know how to write each line back to the file and delete the existing ones in the text file.

Also when I run this code:

file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)

everything works and the line order is reversed, but when I run this code:

text_file = open(file_name, "w")
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
for line in file_lines:
    text_file.write(line)

it prints empty lists for some reason.


Solution

  • You can fix it by doing just 2 little changes in your script.

    1. Use \r+ in place of \w+

    2. Before performing write operation, place file position indicator to the beginning

      text_file.seek(0)

    » rw_file.txt - before operation

    here's a sentence
    look! another one
    here's a third one too
    and another one
    one more
    

    Below is your modified script to reverse the content of file (It worked).

    def reverseFile(file_name):
        text_file = open(file_name, "r+") # Do not use 'w+', it will erase your file content 
        file_lines = [line.rstrip('\n') for line in text_file.readlines()]
        file_lines.reverse()
        print(file_lines)
    
        text_file.seek(0) # Place file position indicator at beginning
    
        for line_item in file_lines:
            text_file.write(line_item+"\n")
    
    
    reverseFile("rw_file.txt")
    

    » rw_file.txt - after operation

    one more
    and another one
    here's a third one too
    look! another one
    here's a sentence