iT邦幫忙

0

python 換行寫入 txt檔

  • 分享至 

  • twitterImage

各位先進 晚上好! 目前在python上遇到輸出txt檔的問題
list_float是列表形式,在遍歷後將列表逗號改為空白,但希望在寫入txt檔時可以透過換行來寫入,目前程式如下

file=open('101.txt','w')#
file.close() 
for i in list_float: #
    ...
    print(i,end=' ',file=open('101.txt','a')) 

在網路上找了很多資料有關寫入的方式或是在寫入前就做換行的處理,都沒找到有效的解決方法,結果如下圖
https://ithelp.ithome.com.tw/upload/images/20191022/201216581SmVq8uXUK.jpg
希望將內容每做一次寫入就換行在寫入下一次的結果,而不是接在後面寫入結果
https://ithelp.ithome.com.tw/upload/images/20191022/20121658T4oVgAKZI7.jpg
感恩各位先進指教 謝謝!

ccutmis iT邦高手 2 級 ‧ 2019-10-22 22:34:08 檢舉
樓主請不要用記事本處理文字檔,建議改用 visual studio code 或是 notepad ++ (這兩個文字編輯器都是不用錢的),用內建的記事本有一個很固人怨的地方就是它會用你的OS的預設編碼當作開啟時的文件編碼(例如Big5),還有在python處理輸出文字檔換行時會遇到很煩人的該用\r\n或\n的問題…等等,總之最好別用,這裡有個vs code新手安裝設定教學 給你參考:
https://www.youtube.com/watch?v=D3CDmRjPdcE
https://www.youtube.com/watch?v=u21W_tfPVrY
a4761533 iT邦新手 5 級 ‧ 2019-10-23 18:21:49 檢舉
感謝C大 有再修正利用notepad++ 謝謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
dragonH
iT邦超人 5 級 ‧ 2019-10-22 21:42:02
list_float = [1, 2, 3, 4, 5]
for i in list_float:
    print(i,end=' \n',file=open('101.txt','a')) 

result

1
2
3
4
5

這樣是你要的嗎

如果是的話

恩..

看更多先前的回應...收起先前的回應...
a4761533 iT邦新手 5 級 ‧ 2019-10-22 22:15:10 檢舉

你好 這結果不是我要的 他會將所有的結果都做換行
但我希望說將一個串列的結果做完再做換行的動作

dragonH iT邦超人 5 級 ‧ 2019-10-22 22:22:15 檢舉

a4761533

你的一個串列是指什麼

資料是長怎麼樣呢

希望將內容每做一次寫入就換行在寫入下一次的結果

"一次" 的定義是什麼

ccutmis iT邦高手 2 級 ‧ 2019-10-22 22:29:06 檢舉

麻倉葉 剛剛跟我說他要的可能是像這樣子...
test.txt

11,22,33,44,55
66,77,88,99,00
11,22,33,44,55
66,77,88,99,00
11,22,33,44,55

test.py

with open("test.txt","r",encoding="utf-8") as f:
    list_float=f.read().split('\n')
f.close()

file=open('101.txt','w')
for i in list_float:
    file.writelines(i.replace(","," ")+"\n")

輸出結果(101.txt)

11 22 33 44 55
66 77 88 99 00
11 22 33 44 55
66 77 88 99 00
11 22 33 44 55
dragonH iT邦超人 5 級 ‧ 2019-10-22 22:35:50 檢舉

/images/emoticon/emoticon56.gif/images/emoticon/emoticon56.gif/images/emoticon/emoticon56.gif

a4761533 iT邦新手 5 級 ‧ 2019-10-22 23:03:08 檢舉

list_float=[[1,2,3],[4,5,6]]
想要輸出txt
1 2 3
4 5 6

a4761533 iT邦新手 5 級 ‧ 2019-10-22 23:06:58 檢舉

但現在發現經過程式有可能[1,2,3][4,5,6]
經list_float 可能是一維的形式

串列耶 (筆記學習

ccutmis iT邦高手 2 級 ‧ 2019-10-23 07:52:17 檢舉

只要有規則可循就能寫程式解決

list_float=[[1,2,3],[4,5,6]]

file=open('101.txt','w')
for i in list_float:
    print(' '.join([str(x) for x in i]))
    file.writelines(' '.join([str(x) for x in i])+"\n")
file.close()

另外樓主先前提到要把','用' '取代(在遍歷後將列表逗號改為空白)讓我誤以為你是讀入csv文字檔類的資料,若是在串列裡面的 , 那個是串列元素的分隔符號,跟字串裡面的','是兩種東西...

dragonH iT邦超人 5 級 ‧ 2019-10-23 09:16:57 檢舉

只要有規則可循就能寫程式解決

/images/emoticon/emoticon32.gif

只要知道你 "一次" 的定義是啥

就很簡單改了

我要發表回答

立即登入回答