转置文件夹中的所有csv文件

Adr*_*mah 4 python csv

上次我在这个网站上提出一个关于使用glob.glob()Python 批量处理文件夹中的csv文件的问题时,我得到了帮助.我这次尝试使用它来转置文件夹中的所有csv文件.下面的脚本只处理最后一个文件并停止.我究竟做错了什么?

import csv
import os
import glob

directory = raw_input ("INPUT Folder")
output = raw_input("OUTPUT Folder:")
in_files = os.path.join(directory, '*.csv')

for in_file in glob.glob(in_files):
    with open(in_file) as input_file:
        reader = csv.reader(input_file)
        cols = []
        for row in reader:
            cols.append(row)
            filename = os.path.splitext(os.path.basename(in_file))[0] + '.csv'

with open (os.path.join(output, filename), 'wb') as output_file:
    writer = csv.writer(output_file)
    for i in range(len(max(cols, key=len))):
        writer.writerow ([(c[i] if i<len(c) else '') for c in cols])
Run Code Online (Sandbox Code Playgroud)

nak*_*tic 5

您需要缩进代码的"输出"部分,以便它为循环的每次迭代运行一次for in_file:

import csv
import os
import glob

directory = raw_input ("INPUT Folder")
output = raw_input("OUTPUT Folder:")
in_files = os.path.join(directory, '*.csv')

for in_file in glob.glob(in_files):
    with open(in_file) as input_file:
        reader = csv.reader(input_file)
        cols = []
        for row in reader:
            cols.append(row)

    # "outdent" this code so it only needs to run once for each in_file
    filename = os.path.splitext(os.path.basename(in_file))[0] + '.csv'

    # Indent this to the same level as the rest of the "for in_file" loop!
    with open (os.path.join(output, filename), 'wb') as output_file:
        writer = csv.writer(output_file)
        for i in range(len(max(cols, key=len))):
            writer.writerow ([(c[i] if i<len(c) else '') for c in cols])
Run Code Online (Sandbox Code Playgroud)

在您的版本中,代码仅在for in_file循环完成后运行一次,因此仅输出cols从该循环的最后一次迭代中遗留的数据.

我还将filename = ...语句"缩进" 到for in_file关卡,因为这只需要为每个语句执行一次in_file,而不是每次都row执行一次in_file.