.Txt文件到Python中的.CSV文件转换

时间:2018-01-15 05:09:42

标签: python-2.7

我正在编写下面的python脚本,其任务是“它将采取.txt文件中存在的任何数据并将其加载到.csv文件中作为输出。我的代码工作但问题是一切都以行的形式出现在CSV输出中。

以下是我的代码: -

# - * - 编码:utf- 8 - * -

import os.path

 import csv

save_path = "C:\Users\desktop\Python-testing\"

completeName_in  = os.path.join(save_path,'Input_file'+'.txt')

completeName_out = os.path.join(save_path,'Output_file_csv'+'.csv')


file1=open(completeName_in)

In_text = csv.reader(file1,delimiter = ';')

file2 =open(completeName_out,'w')

out_csv = csv.writer(file2)

file3 = out_csv.writerows(In_text)

file1.close()

file2.close()

=====================================

我在输入文件中提供以下数据: -

Line no: 1

Line: This is Line1

Line no: 2 

Line: This is Line2

Line no: 3

Line: This is Line3

=====================================

以下是我目前的CSV输出: -

Line no: 1

Line: This is Line1

Line no: 2 

Line: This is Line2

Line no: 3

Line: This is Line3

====================================

但我希望我的输出应该是以CSV格式下面的格式: -

Line no:          Line:

 1             This is Line1

 2             This is Line1

 3             This is Line1

=====================================

任何建议都会有很大帮助。

谢谢 Chinmay

1 个答案:

答案 0 :(得分:0)

我通过首先将输入转换为字典然后将dict转换为csv来实现此目的。这是完整的代码 -

with open(completeName_in, 'r') as csvfile:
    In_text = csv.reader(csvfile, delimiter=':')
    all_rows = []
    row_dict = {}
    count_row = 1
    for row in In_text:
        if len(row) > 0:
            row_dict[row[0].strip()] = row[1].strip()
            if count_row % 2 == 0:
                all_rows.append(row_dict)
                row_dict = {}
            count_row += 1
print(all_rows)
keys = all_rows[0].keys()
print(keys)
with open(completeName_out, 'w', newline='') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(all_rows)

观察结果

  1. 尝试在/中的字符串文字中使用前斜杠save_path

  2. 根据OP输入,有一些空行,所以用len(row)>0条件处理。

  3. 让我知道这是否有效