2017-02-23 281 views
1

我有一個文本文件,我想將它的內容寫入CSV文件中的特定列。 這裏是我的代碼將文本文件寫入CSV文件中的特定列

import csv 
f1 = open ("input.txt","r") # open input file for reading 
f = f1.read() 

with open('output.csv','w') as csvfile: # input csv file 
      a = csv.writer(csvfile, delimiter=',') 

       # edit the 8th column 
      a.writerow(str(f)) 
f1.close() 

的input.txt中: THIS IS文件中的一個

我的問題是,它在一排不完整的句子寫每個字母,我該如何分配給像一個特定的列row[0]有內容。

output.csv(r means row) 
r1 r2 r3 r4  r5 r6 r7 r8 r9 r10 r11 r12 r13 
T H I S  I S F I L E  O N E 
+0

請顯示'input.txt'的內容示例以及您想要'out.csv'的樣子。 – Abdou

+0

我編輯了這個問題並加入了一個例子。 –

+0

是行還是列? – haifzhan

回答

0

我發現this question related到我想要的。我編輯了我的代碼,它的功能非常完美:

import csv 
row = [] 
f1 = open ("input.txt","r") # open input file for reading 
file = f1.read() 
row.append(file) 

with open('output.csv','w', newline='') as csvfile: # input csv file 
      a = csv.writer(csvfile,delimiter=',', quoting=csv.QUOTE_MINIMAL) 
      for i in row: 

        a.writerow([i]) 
f1.close()