gpt4 book ai didi

Python 打印到文件不工作

转载 作者:行者123 更新时间:2023-11-28 16:38:35 26 4
gpt4 key购买 nike

我正在尝试执行这个脚本:

text_file = open("/Users/test/Test/test.txt", "r")
f = open('/Users/test/TEST/test2.txt','w')
list1 = text_file.readlines()
for item in list1:
number=0
while number < 7:
string=str(item)+str(number)
number = number + 1
f.write(string)

文件 test.txt 包含:

a
b
c
d

打开 test2 时的预期输出:

a0
a1
a2
a3
a4
....(actual writing)
d6

实际输出:

a
0a
1a
2a
3a
4b
0b
1b
2b
3b
4c
0c
1c
2c
3c
4d0d1d2d3d4

到底发生了什么?任何帮助将不胜感激

最佳答案

您忘记从 item 中删除 '\n'。使用 str.rstrip为此。

for item in list1:
for number in xrange(7):
string = item.rstrip() + str(number)
f.write(string + '\n')

关于Python 打印到文件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com