将1000个文本文件转换为单个csv文件 [英] Converting 1000 text files into a single csv file

查看:115
本文介绍了将1000个文本文件转换为单个csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个文本文件转换为单个csv文件.文本被命名为(file1.txt,file2.txt .... file1000.txt).文本文件(file1.txt)格式如下:

I want to convert multiple text files into a single csv file.the text are named as(file1.txt,file2.txt....file1000.txt). A text file(file1.txt) format is as follows:

Employee id: us51243
Employee name: Mark santosh
department:engineering
Age:25 

我希望输出为:

Employee id,Employee name,department,Age
us51243,Mark santosh,engineering,25//(file1.txt values)
...................................//(file2.txt values)

但是在输出中,我仅按以下方式获取file1000.txt的值:

But in the ouput I am getting the value of file1000.txt only as follows:

Employee id,Employee name,department,Age
us98621,Andy Gonzalez,Support & services,25

这是我的代码:

import csv
import os
for x in range(1,1001):
    filepath=os.path.normpath('C:\\Text\\file{}.txt'.format(x))
    with open(filepath) as f, open('emp.csv', 'w',newline='') as file:
        writer = csv.writer(file)
        val = zip(*[l.rstrip().split(': ') for l in f])
        writer.writerows(val)

请注意:我也只想显示标题(员工编号,员工姓名,部门,年龄)一次

Kindly note:Also I want to display the header(Employee id,Employee name,Department,Age) only once

推荐答案

您当前正在为每个新的文本文件重新打开文件,这将导致所有内容被覆盖.另外,通过将定界符指定为<​​c0>并跳过任何多余的空格,您也可以使用CSV库读取文本文件:

You are currently reopening your file for each new text file which is causing all the contents to be overwritten. Also, you could use the CSV library to read your text files too by specifying the delimiter as : and skipping any extra spaces:

import csv
import os

header = ["Employee id", "Employee name", "department", "Age"]

with open('emp.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)

    for x in range(1, 1001):
        filepath = os.path.normpath(r'C:\Text\file{}.txt'.format(x))

        with open(filepath, 'r', newline='') as f_text:
            csv_text = csv.reader(f_text, delimiter=':', skipinitialspace=True)
            csv_output.writerow(row[1] for row in csv_text)

这篇关于将1000个文本文件转换为单个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆