简体   繁体   English

,python中文件读写相关问题

[英],Problems related to file reading and writing in python

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

I have some inspiration.我有一些灵感。 Because line = line[::-1], so The resulting file has the same number of list elements as the original file.因为 line = line[::-1],所以生成的文件与原始文件具有相同数量的列表元素。 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.那么,为什么有一个空行以及如何删除它。

Each line that you read from the input file ends with a newline character ('\n').从输入文件中读取的每一行都以换行符 ('\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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM