【问题标题】:Converting a list of txt files into a list of csv files with python使用python将txt文件列表转换为csv文件列表
【发布时间】:2020-07-31 18:00:57
【问题描述】:

我有将单个 .txt 文件转换为单个 .csv 文件的滚动代码,但我需要代码来遍历 .txt 文件的目录并给出相同的 .txt 文件的目录,但在 . csv 格式。

import csv

textfile = 'X:/general/DavidOrgEcon/GSTT/text to csv/Group.txt'
outfile = 'X:/general/DavidOrgEcon/GSTT/text to csv/Group.csv'

with open(textfile, '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 % 4 == 0:
                all_rows.append(row_dict)
                row_dict = {}
            count_row += 1
print(all_rows)
keys = all_rows[0].keys()
print(keys)
with open(outfile, 'w', newline='') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(all_rows)

【问题讨论】:

  • 你试过写for循环吗?

标签: python loops csv


【解决方案1】:

所以假设你有你现有的功能

def text_to_csv(infilepath, outfilepath):
    ...

它可以从 infilepath 读取文本文件并将 csv 输出到 outfilepath,然后您可以创建一个新函数,该函数接受两个目录并首先在每个文本文件上调用它:

import os 

def convert_directory(in_dir, out_dir):
    # Loop through every file in the directory
    for filename in os.listdir(in_dir):
        # Split the file name into a base portion and an extension
        # e.g. "file.txt" -> ("file", ".txt")
        base_name, extension = os.path.splitext(filename)
        # If it is a text file, do the transformation
        if extension == ".txt":
            # Construct the name of the csv file to create
            csv_filename = f"{base_name}.csv"
            # Call your function with the full filepaths
            text_to_csv(
                os.path.join(in_dir, filename),
                os.path.join(out_dir, csv_filename)
            )

convert_directory(
    "X:/general/DavidOrgEcon/GSTT/text to csv/input_dir", 
    "X:/general/DavidOrgEcon/GSTT/text to csv/output_dir",
)

【讨论】:

    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 2018-01-14
    • 2013-09-17
    • 2019-10-17
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多