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而不是字符串连接,+ 这解释了原因。
添加回答
举报