![](/img/trans.png)
[英]How to convert tab separated, pipe separated to CSV file format in Python
[英]Python - save csv file with tab separated words in separate cell
我有這個輸入文件:
one\tone
two\ttwo
three\tthree
每個單詞之間帶有一個制表符。
我試圖將其保存在一個csv文件中,其中每個單詞都以其自己的單元格結尾。 這是我的代碼:
import csv
input = open('input.txt').read()
lines = input.split('\n')
with open('output.csv', 'w') as f:
writer = csv.writer(f)
for line in lines:
writer.writerow([line])
但是,兩個單詞最終都在同一個單元格中:
如何更改代碼,使每個單詞都以自己的單元格結尾?
嘗試這個:
import csv
input = open('input.txt').read()
lines = input.split('\n')
with open('output.csv', 'w') as f:
writer = csv.writer(f)
for line in lines:
writer.writerow(line.split('\t'))
您需要將輸入行拆分為一個列表,以便csv.writer()
將其放入單獨的列中。 嘗試:
with open('output.csv', 'w') as f:
writer = csv.writer(f)
for line in lines:
writer.writerow(line.split('\t'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.