我想使用python將多個csv文件轉換爲txt,而不會丟失列對齊。python - 將csv轉換爲txt而不會丟失列對齊
一個CSV文件,該文件是逗號分隔,沒有空格或製表符的一個例子,顯示如下:
"Products" "Technologies" Region1 Region2 Region3
Prod1 Tech1 16 0 12
Prod2 Tech2 0 12 22
Prod3 Tech3 22 0 36
但是用我的劇本我結束了以下內容:
"Products" "Technologies" Region1 Region2 Region3
Prod1 Tech1 16 0 12
Prod2 Tech2 0 12 22
Prod3 Tech3 22 0 36
分隔符的選擇是任意的。是否有一種相對簡單的方法來實現我想要的功能,考慮到帶有csv文件的表格在維度上會有所不同,並且列標題的長度會有所不同?
我用下面的Python代碼:
import os
import fileinput
dire = "directory"
# function for converting csv files to txt
def csv_to_txt(names, txtfilename):
# remove existing txt file
if os.path.exists(dire + txtfilename + ".txt"):
os.remove(dire + txtfilename + ".txt")
# open the include file
includefile = open(dire + txtfilename + ".txt", "a")
# handle the csv files and convert to txt
with open(names, "a+") as input_file:
lines = [line.split(",", 2) for line in input_file.readlines()]
print lines
text_list = [" ".join(line) for line in lines]
for line in text_list:
includefile.write(line)
includefile.close()
csv_to_txt(dire + "01.csv", "nameofoutputfile")
for line in fileinput.FileInput(dire + "nameofoutputfile" + ".txt",inplace=1):
line = line.replace('"','')
line = line.replace(',',' ')
對不起,我不明白你想要什麼和你現在有什麼不同。 – Allen
在這裏,你的實際和預期的結果都是一樣的。可能是你輸入了錯誤的信息 –
你用什麼代碼編寫你的txt文件? – pingul