Python open() requires full path [duplicate]

2024/10/8 19:49:34

I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

with open('zipcodes.csv', 'r') as zipcode_file:reader = csv.DictReader(zipcode_file)

If I give the full path to the file, it will work. Why open() requires full path of the file ?

Answer

From the documentation:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

So, if the file that you want open isn't in the current folder of the running script, you can use an absolute path, or getting the working directory or/and absolute path by using:

import os
# Look to the path of your current working directory
working_directory = os.getcwd()
# Or: file_path = os.path.join(working_directory, 'my_file.py')
file_path = working_directory + 'my_file.py'

Or, you can retrieve your absolute path while running your script, using:

import os
# Look for your absolute directory path
absolute_path = os.path.dirname(os.path.abspath(__file__))
# Or: file_path = os.path.join(absolute_path, 'folder', 'my_file.py')
file_path = absolute_path + '/folder/my_file.py'

If you want to be operating system agnostic, then you can use:

file_path = os.path.join(absolute_path, folder, my_file.py)
https://en.xdnf.cn/q/70103.html

Related Q&A

Pandas to parquet file

I am trying to save a pandas object to parquet with the following code: LABL = datetime.now().strftime("%Y%m%d_%H%M%S") df.to_parquet("/data/TargetData_Raw_{}.parquet".format(LABL))…

Wildcard in dictionary key

Suppose I have a dictionary:rank_dict = {V*: 1, A*: 2, V: 3,A: 4}As you can see, I have added a * to the end of one V. Whereas a 3 may be the value for just V, I want another key for V1, V2, V2234432, …

How to read emails from gmail?

I am trying to connect my gmail to python, but show me this error: I already checked my password, any idea what can be? b[AUTHENTICATIONFAILED] Invalid credentials (Failure) Traceback (most recent cal…

Python multiprocessing returning AttributeError when following documentation code [duplicate]

This question already has answers here:python multiprocessing in Jupyter on Windows: AttributeError: Cant get attribute "abc"(4 answers)Closed 4 years ago.I decided to try and get into the mu…

Python - How can I find if an item exists in multidimensional array?

Ive tried a few approaches, none of which seem to work for me. board = [[0,0,0,0],[0,0,0,0]]if not 0 in board:# the board is "full"I then tried:if not 0 in board[0] or not 0 in board[1]:# the…

Convert Geo json with nested lists to pandas dataframe

Ive a massive geo json in this form:{features: [{properties: {MARKET: Albany,geometry: {coordinates: [[[-74.264948, 42.419877, 0],[-74.262041, 42.425856, 0],[-74.261175, 42.427631, 0],[-74.260384, 42.4…

Pymongo - ValueError: NaTType does not support utcoffset when using insert_many

I am trying to incrementally copy documents from one database to another. Some fields contain date time values in the following format:2016-09-22 00:00:00while others are in this format:2016-09-27 09:0…

python numpy argmax to max in multidimensional array

I have the following code:import numpy as np sample = np.random.random((10,10,3)) argmax_indices = np.argmax(sample, axis=2)i.e. I take the argmax along axis=2 and it gives me a (10,10) matrix. Now, I …

Can Keras model.predict return a dictionary?

The documentation https://keras.io/models/model/#predict says that model.predict returns Numpy array(s) of predictions. In the Keras API, is there is a way to distinguishing which of these arrays are…

Flask OIDC: oauth2client.client.FlowExchangeError

The Problem: The library flask-oidc includes the scope parameter into the authorization-code/access-token exchange request, which unsurprisingly throws the following error:oauth2client.client.FlowExcha…