[英]Python; open file from path specified with sys.argv
I want to open a csv-file with python from a path that is specified in sys.argv. 我想从sys.argv中指定的路径使用python打开一个csv文件。 The name of the file is 'file.out' and I want to open it from the scriptlocation as specified in sys.argv[2].
该文件的名称为'file.out',我想从sys.argv [2]中指定的脚本位置打开它。 However, I do not know how to specify the scriptlocation in the pd.read_csv command.
但是,我不知道如何在pd.read_csv命令中指定脚本位置。 I tried it as follows, but that does not work.
我尝试了如下操作,但这不起作用。 What is the problem?
问题是什么?
My code is as follows 我的代码如下
outputfolder = sys.argv[1]
scriptlocation = sys.argv[2]
df = pd.read_csv(open(scriptlocation('file.out', 'r')), header=None, delim_whitespace=True)
Try this: 尝试这个:
import os
fn = os.path.join(os.path.dirname(sys.argv[2]), 'file.out')
df = pd.read_csv(fn, header=None, delim_whitespace=True)
If you use Python v3.4+ and Pandas v0.18.1+ you can use pathlib : 如果您使用Python v3.4 +和Pandas v0.18.1 +,则可以使用pathlib :
Demo: 演示:
In [93]: from pathlib import Path
In [94]: p = Path(sys.argv[0])
In [95]: p
Out[95]: WindowsPath('C:/Users/Max/Anaconda3_5.0/envs/py36/Scripts/ipython3')
In [96]: fn = p.joinpath('file.out')
In [97]: fn
Out[97]: WindowsPath('C:/Users/Max/Anaconda3_5.0/envs/py36/Scripts/ipython3/file.out')
This is not a pandas
issue. 这不是
pandas
问题。 What you need is to make a filepath based on a root folder ( scriptlocation
if I understand correctly) and a filename. 您需要基于根文件夹(如果我理解正确,则为
scriptlocation
)和文件名创建文件路径。 You will then pass that constructed filepath to pd.read_csv()
. 然后,您将把构造的文件路径传递给
pd.read_csv()
。 So you are looking for os.path.join()
: 所以您正在寻找
os.path.join()
:
output_fn = os.path.join(scriptlocation , 'file.out')
df = pd.read_csv(output_fn, header=None, delim_whitespace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.