該計劃的目標是:
- 接受2個檔案夾路徑
- 取 1 個整數值
- 驗證兩個檔案夾都在目錄中,并且 Integer 值是 int
- 將指定數量的檔案從源檔案夾移動到目標檔案夾。例如,如果源檔案夾包含 8 個檔案,我想將最后 4 個檔案移動到目標檔案夾。
- 在命令列中: python main.py path1 path2 4
我正處于使用命令列引數而不是默認值占位符(分配給變數的檔案夾路徑和整數值)并通過控制臺運行的測驗階段。
我的問題是:
- 當 path1、path2 和 int 都存在且值正確時,一切都按預期作業
- 如果整數不是 int (例如,python main.py path1 path2 string)程式崩潰并給我錯誤。
- 如果程式讀取 CLI arg 不是 int ( num = int(sys.argv[3]) ) 我想將值默認為 10,但程式似乎沒有這樣做?
錯誤
空白 = 屏蔽個人資訊
python main.py Path1 Path2 L
Traceback (most recent call last):
File "C:\Users\blank\blank\blank\main.py", line 71, in <module>
main()
File "C:\Users\blank\blank\blank\main.py", line 66, in main
read_args()
File "C:\Users\blank\blank\blank\main.py", line 29, in read_args
num = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 'L'
主要的
import os, sys, shutil, time
def main():
read_args()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
exit()
代碼
def validate_folder(folder):
"""Validates folders in working directory"""
try:
isDir = os.path.isdir(folder)
return isDir
except Exception as e:
print(e)
return None
def validate_number(number1):
"""Validates third argument is an integer value"""
try:
int(number1)
return True
except ValueError:
return False
def read_args():
"""Read CLI arguments"""
source_folder = sys.argv[1]
destination_folder = sys.argv[2]
num = int(sys.argv[3])
"""Get main folder and archive folder and validate they are in the directory"""
main_folder = validate_folder(source_folder)
archive_folder = validate_folder(destination_folder)
kept_files = validate_number(num)
"""If any of the inputs is not valid return None proceed with conditional checks"""
if main_folder is False or archive_folder is False:
print("Folders cannot be found")
if main_folder is True and archive_folder is True and kept_files is False:
num = 10
sortFiles_and_moveFiles(source_folder, destination_folder, num)
else:
"""If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
sortFiles_and_moveFiles(source_folder, destination_folder, num)
def sortFiles_and_moveFiles(path1, path2, n_files):
source_folder = path1
destination_folder = path2
"""Get list of all files only in the given directory"""
list_of_files = filter(lambda x: os.path.isfile(os.path.join(source_folder, x)), os.listdir(source_folder))
"""Sort list of files based on last modification time in descending order"""
list_of_files = sorted(list_of_files, key=lambda x: os.path.getmtime(os.path.join(source_folder, x)))
"""Iterate over sorted list of files and print file path, along with last modification time of file"""
for file_name in list_of_files:
file_path = os.path.join(source_folder, file_name)
timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))
print(timestamp_str, ' -->', file_name)
print("Designated files have been moved")
"""Move designated number of files to archive folder using slice notation."""
for file_name in list_of_files[n_files:]:
shutil.move(os.path.join(source_folder, file_name), destination_folder)
uj5u.com熱心網友回復:
如果可以將字串強制轉換為else ,則有一個內置函式str.isdigit()回傳。您的一些 if 檢查也可以縮短TrueintFalse
if main_folder is True and archive_folder is True and kept_files is False:
可以換成簡單的
elif kept_files is False:
但是整個方法仍然可以修改如下
def read_args():
"""Read CLI arguments"""
source_folder = sys.argv[1]
destination_folder = sys.argv[2]
num = sys.argv[3]
"""Get main folder and archive folder and validate they are in the directory"""
main_folder = validate_folder(source_folder)
archive_folder = validate_folder(destination_folder)
"""If any of the inputs is not valid return None proceed with conditional checks"""
if main_folder is False or archive_folder is False:
print("Folders cannot be found")
elif not num.isdigit():
num = 10
else:
"""If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
num = int(num)
sortFiles_and_moveFiles(source_folder, destination_folder, num)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425391.html
