首页 > 解决方案 > Python中带有文件连接的ValueError

问题描述

对 Python 如此陌生。我有一个包含 20,000 个 csv 的文件夹,其中对我很重要的文件夹'IC'prev_date + '.csv'. 我试图找到一种方法将所有这些连接到一个文件中,如果在应用上述开始和结束过滤器时,它会连接。

import os

prev_date = str('20190624')
csv_header = 'Index no,date,thesis,quantity'
csv_out = 'R:/Sam/simulator/consolidated_positions.csv'

csv_dir = 'R:/Sam/simulator/'

dir_tree = csv_dir
for dirpath, dirnames, filenames in dir_tree:
    pass

csv_list = []
for file in filenames:
    if file.endswith(prev_date + '.csv') and file.startswith('IC'):
        csv_list.append(file)

csv_merge = open(csv_out, 'w')
csv_merge.write(csv_header)
csv_merge.write('\n')

for file in csv_list:
    csv_in = open(file)
    for line in csv_in:
        if line.startswith(csv_header):
            continue
        csv_merge.write(line)
    csv_in.close()
    csv_merge.close()
print('Verify consolidated CSV file : ' + csv_out)

问题是我不断在回溯中获取项目文件夹

Traceback (most recent call last):
  File "R:/Sam/Project/Branch/concatanator.py", line 10, in <module>
    for dirpath, dirnames, filenames in dir_tree:
ValueError: not enough values to unpack (expected 3, got 1)

我认为这与预期的相对文件路径有关,而不是我提供的实际路径。

另外,如果可能的话,如果有人在文件名中的任何位置有单词,是否有关于如何排除文件的快速提示EXTRA

标签: pythonpython-3.x

解决方案


尝试更改这行代码

for dirpath, dirnames, filenames in dir_tree:

为此,使用os.walk()

for dirpath, dirnames, filenames in os.walk(dir_tree):

至于你的第二个问题:

另外,如果可能的话,如果有人在文件名中的任何地方都有单词EXTRA,是否有关于如何排除文件的快速提示?

你可以试试这个:

for file in filenames:
    if 'EXTRA' not in file:
        if file.endswith(prev_date + '.csv') and file.startswith('IC'):
            csv_list.append(file)

最终代码(您应该使用它os.path.join(dirpath, file)来获取完整的文件路径):

csv_list = []
for dirpath, dirnames, filenames in os.walk(csv_dir):
    for file in filenames:
        if 'EXTRA' not in file:
            if file.endswith(prev_date + '.csv') and file.startswith('IC'):
                csv_list.append(os.path.join(dirpath, file))

推荐阅读