2 回答

TA貢獻(xiàn)1820條經(jīng)驗 獲得超2個贊
用于join用空格連接列表元素。使用“\n”作為行分隔符。
試試這個代碼:
A= ['1', '2', '3', '4', '5']
B= ['6', '7', '8', '9', '10']
with open('data.txt','w') as f:
f.write(' '.join(A) + '\n' + ' '.join(B))
輸出(數(shù)據(jù).txt)
1 2 3 4 5
6 7 8 9 10
- - 更新 - -
如果你想多次寫入列表,python提供了字符串乘法: mystring*5將寫入mystring5次。
嘗試更改此代碼:
n = 3
with open('data.txt','w') as f:
f.write((' '.join(A)+'\n')*n + (' '.join(B)+'\n')*n) # write each string n times
輸出(數(shù)據(jù).txt)
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
6 7 8 9 10
6 7 8 9 10
6 7 8 9 10

TA貢獻(xiàn)1818條經(jīng)驗 獲得超3個贊
用于' '.join()通過空格加入您的列表。和 '\n' 進(jìn)行換行
嘗試這個:
A= ['1', '2', '3', '4', '5'] # your lists
B= ['6', '7', '8', '9', '10']
f = open("filename.txt","w+") # create your file
f.write(' '.join(A)) # write list A to your file
f.write('\n') # line break
f.write(' '.join(B)) # write list B to your file
文件名.txt:
1 2 3 4 5
6 7 8 9 10
添加回答
舉報