Python 我希望我的.py代码能够全局读取excel文件

Python 我希望我的.py代码能够全局读取excel文件,python,Python,我的代码是 import pandas as pd import os import xlrd os.chdir('H:\python') file_name='H:\python\\test.xlsx' 但我不想在.py文件中指定文件名。python中是否有全局读取文件的选项。是的,您可以。通过接受用户的输入。因此,使用input方法接受excel文件的路径,然后使用该路径 下面的代码将起作用 import pandas as pd file_path = input() df = pd.r

我的代码是

import pandas as pd
import os
import xlrd
os.chdir('H:\python')
file_name='H:\python\\test.xlsx'

但我不想在.py文件中指定文件名。python中是否有全局读取文件的选项。

是的,您可以。通过接受用户的输入。因此,使用
input
方法接受excel文件的路径,然后使用该路径

下面的代码将起作用

import pandas as pd
file_path = input()
df = pd.read_excel(file_path)
编辑:添加另一种方法来执行此操作。在python文件中编写以下代码。假设文件名为
excel\u reader.py

import sys
import pandas as pd
df = pd.read_excel(sys.argv[1])
使用以下命令通过命令行作为参数提供文件

python excel_reader.py "C:\path_to_the_excel_file"

“全局读取文件”是什么意思?请不要让人们使用
input()
@EvgenyPogrebnyak,将代码更新为使用命令行参数。看起来很棒!使用
-i
flag命令行调用可能更有用。我想人们可以使用
python-i excel\u reader.py C://path\u访问\u excel\u文件//file.xls
-这会在初始化
df
后打开解释器。@EvgenyPogrebnyak,因此,我必须使用getopt模块来获得正确的文件名