[英]What do I do to make a python script that can run from any directory: the script file doesn’t have to be in the same directory as the .csv files?
Currently, I have created a code that makes graphs from data in .csv files. 目前,我已经创建了一个代码,可以从.csv文件中的数据制作图形。 However, I can only run the code if that code is present in the folder with the csv files. 但是,如果该代码存在于csv文件的文件夹中,则我只能运行该代码。 How can I make the the script file so that it doesn't have to be in the same directory as the .csv files. 如何制作脚本文件,以使它不必与.csv文件位于同一目录中。
Assuming you mean to include a fixed CSV file with your code, store an absolute path based on the script path: 假设您打算在代码中包含一个固定的CSV文件,请根据脚本路径存储一个绝对路径:
HERE = os.path.dirname(os.path.abspath(__file__))
csv_filename = open(os.path.join(HERE, 'somefile.csv')
__file__
is the filename of the current module or script, os.path.dirname(__file__)
is the directory the module resides in. For scripts, __file__
can be a relative pathname, so we use os.path.abspath()
to turn that into an absolute path. __file__
是当前模块或脚本,的文件名os.path.dirname(__file__)
是模块驻留在目录中。对于脚本, __file__
可以是一个相对路径名,所以我们使用os.path.abspath()
把这一进入绝对路径。
This means you can run your script from anywhere. 这意味着您可以在任何地方运行脚本。
If you meant to make your script work with arbitrary CSV input files, use command line options: 如果要使脚本与任意 CSV输入文件一起使用,请使用命令行选项:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser('CSV importer')
parser.add_argument('csvfile', type=argparse.FileType('w'),
default='somedefaultfilename.csv')
options = parser.parse_args()
import_function(options.csvfile)
where csvfile
will be an open file object, so your import_function()
can just do: 其中, csvfile
将是一个打开的文件对象,因此import_function()
可以执行以下操作:
def import_function(csvfile):
with csvfile:
reader = csv.reader(csvfile)
for row in reader:
# etc.
If you don't plan on moving around the csv files too much, the best answer is to hard code the absolute path to the csv folder into the script. 如果您不打算在csv文件中移动太多,最好的答案是将csv文件夹的绝对路径硬编码到脚本中。
import os
csvdir = "/path/to/csv/dir"
csvfpath = os.path.join(csvdir, "myfile.csv")
csvfile = open(csvfpath)
You can also use a command line parser like argparse
to let the user easily change the path to the csv files. 您还可以使用argparse
类的命令行解析器,使用户轻松更改csv文件的路径。
Using Martijn Pieters's solution will work only if you are going to be moving the folder containing both the script and csv files around. 仅当您要移动包含脚本和csv文件的文件夹时,才能使用Martijn Pieters的解决方案。 However in that case, you may as well just use relative paths to the csv files. 但是,在这种情况下,您也可以只使用csv文件的相对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.