简体   繁体   中英

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. The name of the file is 'file.out' and I want to open it from the scriptlocation as specified in sys.argv[2]. However, I do not know how to specify the scriptlocation in the pd.read_csv command. 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 :

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. What you need is to make a filepath based on a root folder ( scriptlocation if I understand correctly) and a filename. You will then pass that constructed filepath to pd.read_csv() . So you are looking for os.path.join() :

output_fn = os.path.join(scriptlocation , 'file.out')
df = pd.read_csv(output_fn, header=None, delim_whitespace=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM