我希望我的.py代码将全局读取excel文件

时间:2018-06-15 12:23:33

标签: python

我的代码是

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

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

1 个答案:

答案 0 :(得分:1)

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

以下代码将起作用

import pandas as pd
file_path = input()
df = pd.read_excel(file_path)

编辑:添加一种方法来执行此操作。在python文件中编写以下代码。假设文件名为excel_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"