簡體   English   中英

Python打印到文件不起作用

[英]Python Print to File Not Working

我正在嘗試執行此腳本:

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM