我需要在我的 python 模塊中實作以下目標。
- 通過 argparse 模塊獲取目錄作為引數
- 使用該目錄來遍歷該目錄中存在的所有檔案。
- 稍后,僅將 CSV 檔案附加到字典并將它們存盤在那里。
我試過 os.walk,但它沒有回傳任何東西。
我已經撰寫了代碼來獲取一個目錄作為輸入,然后遍歷它以獲取檔案。但它會引發錯誤。
下面是代碼
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專家。
uj5u.com熱心網友回復:
我將files_dir = {}線路改為
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")
uj5u.com熱心網友回復:
您可以使用此代碼`
import os
files = os.listdir("/path_to_directory")
csv = list(filter(lambda f: f.endswith('.csv'), files))
csv 包含所有帶有 .csv 擴展名的檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471701.html
上一篇:為什么此代碼片段存在分段錯誤?
