Python อัตโนมัติเสร็จสมบูรณ์จากโฟลเดอร์ [ซ้ำ]

Aug 26 2020

เมื่อเร็ว ๆ นี้ฉันเล่นกับ python และได้สร้างไฟล์ python ที่อ่านจากไฟล์ในไดเร็กทอรีเฉพาะ ไฟล์เฉพาะที่จะอ่านจะถูกส่งผ่านจากบรรทัดคำสั่ง:

import sys
DIR = /path/to/files
with open(DIR + sys.argv[1]) as fil:
    print(fil.readlines())

# python testPy.py fileName
# >>> prints contents of file

ฉันอยากรู้ว่ามีวิธีที่ฉันสามารถใส่ชื่อไฟล์ในไฟล์ DIR

คำตอบ

Ajordat Aug 26 2020 at 05:35

ไม่ใช่ฟังก์ชันการเติมข้อความอัตโนมัติโดยตรง แต่คุณสามารถแสดงรายการเนื้อหาทั้งหมดในไดเร็กทอรีและค้นหาไฟล์ / โฟลเดอร์ทั้งหมดที่เริ่มต้นด้วยอินพุตที่ผู้ใช้ระบุ ด้วยวิธีนี้หากพบเพียงค่าเดียวนั่นเป็นไปได้เพียงอย่างเดียวและคุณจะพบไฟล์ที่เล็งไว้

รหัสควรเป็นดังนี้:

import os

DIR = "/path/to/files"
content = os.listdir(DIR)
filename = sys.argv[1]

candidates = [path for path in content if path.startswith(filename)]

if len(candidates) == 1:
    print(os.path.join(DIR, candidates[0]))
elif len(candidates) > 1:
    print(f"Multiple options: {candidates}")
else:
    print(f"There are no files starting with '{filename}'")