Home > Net >  ,Problems related to file reading and writing in python
,Problems related to file reading and writing in python

Time:07-03

I want to reverse each line in a file and write it in another file. In my result, there with a space at the beginning, and the last two lines of the result are concatenated. This is my code below.Thanks a lot!

with open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\data.csv") as fi,\
        open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\reverseline.txt","w ") as fo:
    txt=fi.readlines()
    for line in txt:
        line = line[::-1]
        fo.write(line)

This is origin file:

1,2,3,4,5,6,7
8, 3, 2, 7, 1, 4, 6, 5
6, 1, 3, 8, 5, 7, 4, 2
'a','b','c','x','y','z','i','j','k'
'k', 'b', 'j', 'c', 'i', 'y', 'z', 'a', 'x'
'z', 'c', 'b', 'a', 'k', 'i', 'j', 'y', 'x'
'a', 'y', 'b', 'x', 'z', 'c', 'i', 'j', 'k'
5, 2, 4, 7, 1, 6, 8, 3

This is my incorrect result:

(A blank line in there)
7,6,5,4,3,2,1
5 ,6 ,4 ,1 ,7 ,2 ,3 ,8
2 ,4 ,7 ,5 ,8 ,3 ,1 ,6
'k','j','i','z','y','x','c','b','a'
'x' ,'a' ,'z' ,'y' ,'i' ,'c' ,'j' ,'b' ,'k'
'x' ,'y' ,'j' ,'i' ,'k' ,'a' ,'b' ,'c' ,'z'
'k' ,'j' ,'i' ,'c' ,'z' ,'x' ,'b' ,'y' ,'a'3 ,8 ,6 ,1 ,7 ,4 ,2 ,5

This is the result I want:

7,6,5,4,3,2,1
5 ,6 ,4 ,1 ,7 ,2 ,3 ,8
2 ,4 ,7 ,5 ,8 ,3 ,1 ,6
'k','j','i','z','y','x','c','b','a'
'x' ,'a' ,'z' ,'y' ,'i' ,'c' ,'j' ,'b' ,'k'
'x' ,'y' ,'j' ,'i' ,'k' ,'a' ,'b' ,'c' ,'z'
'k' ,'j' ,'i' ,'c' ,'z' ,'x' ,'b' ,'y' ,'a'
3,8,6,1,7,4,2,5

CodePudding user response:

I have some inspiration. Because line = line[::-1], so The resulting file has the same number of list elements as the original file. Because there is an empty line at the beginning, so the last line has no place, so it is connected to the previous line, resulting in this result. well,so why there is an empty line and how can I remove it.

CodePudding user response:

Each line that you read from the input file ends with a newline character ('\n'). Therefore, when you reverse the characters the newline is at the beginning.

Therefore:

with open('input.txt') as infile, open('output.txt', 'w ') as outfile:
    for line in infile.readlines():
      rev = line[::-1]
      o = rev[0] == '\n'
      print(rev[o:], file=outfile)
  • Related