编写代码以迭代目录中的所有文件,并将每个文件的路径附加到字典中



我需要在我的python模块中实现以下目标。

  1. 通过argparse模块获取一个目录作为参数
  2. 使用该目录遍历该目录下的所有文件。
  3. 之后,只将CSV文件追加到字典中并存储在那里。

我试过os。运行,但不返回任何东西。

我已经编写了代码来获取目录作为输入,然后通过它迭代文件。但是会抛出错误。

下面是代码
import argparse
import os
import re

# Accepting arguments for source_directory, my_sql connection details and table name to 
update the MySQL entries to

parser = argparse.ArgumentParser(
description='Utility to update MySQL tables on remote host')
parser.add_argument('-s', '--source_dir', help='Enter Path For CSV File')

args = parser.parse_args()

# Empty dictionary to store list CSV files in directory
files_in_dir = {}

# Function to iterate through the source_directory and read-only CSV files and append them 
to files_in_dir dictionary

if args.source_dir:
for file in args.source_dir:

if os.path.abspath(file.name).endswith('.csv'):
files_in_dir[(os.path.abspath(file.name))] = 0

else:
print("The file %s is not a .csv file and it will be ignored" % (file.name))

print(files_in_dir)

这是通过终端执行时的错误。

python3 sourcecheck.py -s /home/thepredator/Desktop/VOIS/csv_files/*
usage: sourcecheck.py [-h] [-s SOURCE_DIR]
sourcecheck.py: error: unrecognized arguments: /home/thepredator/Desktop/VOIS/csv_files/Book1.csv /home/thepredator/Desktop/VOIS/csv_files/Build.py /home/thepredator/Desktop/VOIS/csv_files/car_data.csv /home/thepredator/Desktop/VOIS/csv_files/db.py /home/thepredator/Desktop/VOIS/csv_files/Edited.csv /home/thepredator/Desktop/VOIS/csv_files/Iris.csv /home/thepredator/Desktop/VOIS/csv_files/Lab_Python_for_Data_Analytics.ipynb /home/thepredator/Desktop/VOIS/csv_files/startupNaN.csv /home/thepredator/Desktop/VOIS/csv_files/startupog.csv /home/thepredator/Desktop/VOIS/csv_files/text.csv

我通过观看不同的视频编写了上面的代码。请帮我修正错误。而且,我不是python专家。

我把files_dir = {}line改成

files_in_dir = { key:0 for key in os.listdir(args.source_dir) if os.path.abspath(key).endswith(".csv") }

这似乎是有效的。

if-else in for语句版本:

for key in os.listdir(args.source_dir):
if os.path.abspath(key).endswith(".csv"):
files_in_dir[key] = 0
else:
print(f"The file {key} is not a .csv file and it will be ignored")

您可以使用以下代码'

import os
files = os.listdir("/path_to_directory")    
csv = list(filter(lambda f: f.endswith('.csv'), files))

csv包含所有扩展名为。csv的文件

最新更新