修改CSV档案? [英] Modify csv files?

查看:116
本文介绍了修改CSV档案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Python修改位于同一文件夹/目录中的所有csv文件(总共240个)? csv文件包含测试结果,这些结果全部列在第一列而不是几列中.经过修改后,我想用所有csv文件的分号(;)替换逗号(,),以获得下面的示例B):

Is it possible to modify all csv-files (240 in total) which are located in the same folder/directory with Python? The csv files consist test results and these are listed all in the first column instead of several columns. With the modification I would like to replace the comma (,) with a semicolon (;) of all csv files to get example B) below:

A)一个csv文件的内容示例(通过Python脚本进行修改之前):

A) Content example of one csv-file (before modification via Python script):

Column A:              Column B:   Column C:   Column D:   Column E:
1, 65, 165, 484, 15,
0, 46, 49, 4, 66,

B)一个csv文件的内容示例(通过Python脚本修改后的 ):

B) Content example of one csv-file (after modification via Python script):

Column A:   Column B:   Column C:   Column D:   Column E:
1           65          165         484         15
0           46          49          4           66

我还没有找到任何例子.你已经实现了类似的东西吗?还是有比Python更好的解决方案?我知道您可以在Excel中完成此操作,但我不想重复240次.

I haven't found any example yet. Have you implemented something like that already? Or is there a better solution then Python? I know you can do it in Excel, but I don't want do repeat that 240 times.

更新:我的解决方案

我用下面的代码做到了,并且可以正常工作.但是在每一行之间我有一个空行.我不明白为什么?

I did it with the following code and it works. But between each row I have an empty row. I don't understand why??

with open('_' + csv_name, mode="w") as outfile:
    writer = csv.writer(outfile, delimiter=';')
    with open(csv_name, mode="rU") as infile:
        print(csv_name)
        reader = csv.reader(infile, dialect="excel")
        for row in reader:
            print(row)
            writer.writerow(row)

每个与* .py文件被修改的文件夹相同的csv文件.

Every csv-file int the same folder as the *.py file is modified.

推荐答案

首先,您需要找到目录中所有CSV文件的文件:

well firstly you need to find all the files in your directory that are CSV files:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        #here is where we will process each file

现在要处理每个需要打开的文件:

now to process each file you need to open it:

csv_file = open(file, mode="r")

现在我们可以读取数据了:

now we can read in the data:

data = file.readlines()

然后再次关闭文件:

csv_file.close()

假设您要就地编辑它们(文件名没有更改) 在写入模式下重新打开同一文件:

assuming you want to edit them in place(no filename changes) reopen the same file in write mode:

csv_file.open(file, mode="w")

现在我们处理数据:

for line in data:
    file.write(line.replace(",",";"))

现在我们再次关闭文件:

and now we close the file again:

csv_file.close()

并且因为这都是"for file in ..."循环的全部内容,因此将对目录中以".csv"结尾的每个文件重复此操作

and as this is all inside out 'for file in ...' loop this will be repeated for each file in the directory that ends with '.csv'

这篇关于修改CSV档案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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