列の配置を失うことなく、複数のcsvファイルをPythonを使用して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