提问人:RykerStrike 提问时间:11/10/2023 更新时间:11/10/2023 访问量:40
为什么我的输出文件将前两行合并在一起,如何将它们分开?
Why does my output file combine the first two lines together, and how can I separate them?
问:
每当我运行该程序时,它都会组合我列表中的前两项。这是我输入文件中的内容:
programming
python
world
hello
输出文件返回:
programmingpython
world
hello
这是我需要的输出:
programming
python
world
hello
这是任务:假设我们有一个文件 words.txt,其中包含一个英语单词列表,每行一个单词。编写将从该文件中读取单词并将这些单词以相反顺序写入输出文件out_words.txt的 Python 程序。也就是说,输入文件中的最后一个单词应该是输出文件中的第一个单词,依此类推。
这就是我到目前为止所拥有的:
in_file = open("words.txt", "r")
out_file = open("out_words.txt", "w")
L = []
for line in in_file:
L == L.append(line)
reverse = L[::-1]
string = "".join(reverse)
print(string, file=out_file)
in_file.close()
out_file.close()
答:
-1赞
linpingta
11/10/2023
#1
你不应该将 L 设置为 L.append 的返回值,也不需要将反向操作放在迭代中(我猜当你在这里复制代码时它是拼写)
尝试如下代码:
in_file = open("words.txt", "r")
out_file = open("out_words.txt", "w")
# Read all of the words from the input file into a list.
L = []
for line in in_file:
L.append(line)
reverse = L[::-1]
with open("out_words.txt", "w") as out_file:
for word in reverse:
print(word, file=out_file)
in_file.close()
out_file.close()
评论
0赞
RykerStrike
11/10/2023
我找到了一种方法,但您的代码确实有所帮助,谢谢!
0赞
blhsing
11/10/2023
这个答案根本没有解决问题的主要问题,即最后两个词在输出中连接在一起。
0赞
RykerStrike
11/10/2023
#2
这就是我最终得到的,我不知道它是否有意义,但它有效
in_file = open("words.txt", "r")
out_file = open("out_words.txt", "w")
L = []
for line in in_file:
L.append(line)
reverse_string = L[::-1]
string = " ".join(reverse_string).split()
for item in string:
print(item, file=out_file)
in_file.close()
out_file.close()
0赞
blhsing
11/10/2023
#3
您得到的前两个单词连接在一起的输出的原因是您的输入文件不以换行符结尾,因此当您将行反转为字符串列表,然后用空字符串连接它们时,没有换行符的最后一行将与没有分隔符的倒数第二行连接。
可以使用 str.splitlines
方法按换行符拆分文件内容,但不要将换行符保留在返回的字符串列表中。通过将输入行规范化为不带换行符,您可以使用以下命令轻松地以相反的顺序输出列表,并使用换行符作为分隔符:print
with open('words.txt') as in_file, open("out_words.txt", "w") as out_file:
print(*reversed(in_file.read().splitlines()), sep='\n', file=out_file)
评论
L[::-1]