2 回答

TA貢獻1875條經驗 獲得超5個贊
您可以按照自己喜歡的方式進行操作,但讓用戶寫出文件的完整路徑既乏味又容易出錯。你可以做的是有一個“監視文件夾”。這是您的腳本已經知道的文件夾,甚至可能與您的腳本位于同一文件夾中。
一個小例子:
import os
import sys
# This prints the folder where the script is run.
script_directory = os.path.dirname(sys.argv[0])
print(script_directory)
# This is the folder we want to keep track off
our_watched_folder = f'{script_directory}/watch_folder'
print(our_watched_folder)
# Let's see if a user dropped a new file in our folder
print("Files in watch folder")
for file in os.listdir(our_watched_folder):
print(file)
輸出:
C:/your_script_folder/
C:/your_script_folder/watch_folder
Files in watch folder
a_new_text_file.txt
some_old_textfile1.txt
some_old_textfile2.txt

TA貢獻1786條經驗 獲得超11個贊
from pathlib import Path
data_folder = Path(str(input("type the path you would like to use")))
file_to_open = data_folder / str(input("insert the file you would like to use with its extension"))
f = open(file_to_open)
如果您不想使用完整路徑而只想使用位于腳本位置的本地文件,您只需要詢問用戶其名稱并f = open(filename)直接打開它。
注意:如果您想知道為什么有/infile_to_open而不是字符串連接,+ 這解釋了原因。
添加回答
舉報