Trying to open a csv file that lives in the same directory as my Python script, but getting error2 file doesn't exist?
One approach would be to set the working directory to be the same location as where your script is. To do this for any script, add this to the top:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
This takes the full name of where your script is located, takes just the path element and sets the current working directory to that.
You then would not need to specify the full path to your file.
Opening a file with python in the same directory from different locations
Use __file__
to get the path to the current script file, then find the file relative to that:
# In main.py: find the file in the same directory as this script
import os.path
open(os.path.join(os.path.dirname(__file__), 'file.txt'))
# In Test/test.py: find the file one directory up from this script
import os.path
open(os.path.join(os.path.dirname(__file__), '..', 'file.txt'))
Why doesn't my script printing the contents of my file?
Your code looks okay, so to eliminate the possibility that the active directory of the script is not the same as the script'sactual location, give the full path to the file.
Also, it's safer to open files like this:
path = "/full/path/to/the/file/pride.txt"
with open(path, "rt", encoding="UTF-8") as f:
s = f.read()
print("Contents of file:", s)
Run a script in the same directory as the current script
Since $0
holds the full path of the script that is running, you can use dirname
against it to get the path of the script:
#!/bin/bash
script_name=$0
script_full_path=$(dirname "$0")
echo "script_name: $script_name"
echo "full path: $script_full_path"
so if you for example store it in /tmp/a.sh
then you will see an output like:
$ /tmp/a.sh
script_name: /tmp/a.sh
full path: /tmp
so
- Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with
/usr/bin/script.sh
, with./script.sh
, or it could be with
../Downloads/repo/scr/script.sh
)
Using dirname "$0"
will allow you to keep track of the original path.
- The script
script.sh
will be changing to a different directory before callinghelper.sh
.
Again, since you have the path in $0
you can cd
back to it.
I tried to put the files on the same folder but still gives an error when using open()
Being totally honest, it's true that there's a lack of information. You might have typed your folder structure or where the file is.
Is it in the directory you are running the script? Then your sintax should work flawlessly unless you are using a an IDE such as VSCode, in that case if you don't open the folder your .py
and .txt
are in, it assumes you are C:\Users\%username%\
. So your code is correct but the directory you are looking for is wrong.
You can avoid this by avoiding relative paths and working with absolute paths such r'C:\Users\FirstName.LastName\Documents\myFile.txt'
You can think about the relative path you are using as an 'autocomplete' that looks up in the directory you are running the script in.
Being absolutely honest with you, I would avoid importing libraries for mundane tasks if you aren't worrying about performances, and this doesn't seem the case at all. So just go with:
absolute_path = r'C:\Users\FirstName.LastName\Documents\myFile.txt'
with open(absolute_path, 'r') as file:
reader = file.read()
Related Topics
How to Run an External Command Asynchronously from Python
Apt-Get Install for Different Python Versions
Creating Same Random Number Sequence in Python, Numpy and R
Sort List of Lists Ascending and Then Descending
What's the Difference Between Select_Related and Prefetch_Related in Django Orm
Pip Install Access Denied on Windows
Efficient Way to Apply Multiple Filters to Pandas Dataframe or Series
Subprocess.Popen: Cloning Stdout and Stderr Both to Terminal and Variables
Python Creating a Dictionary of Lists
Windows Scipy Install: No Lapack/Blas Resources Found
Running a Linux Command from Python
Oserror: Cannot Load Library 'C:\Program Files\R\R-4.0.2\Bin\X64\R.Dll': Error 0X7E
Caesar Cipher Function in Python
Matplotlib: Format Axis Offset-Values to Whole Numbers or Specific Number
Installing Python Packages from Local File System Folder to Virtualenv with Pip
Python: Get a Frequency Count Based on Two Columns (Variables) in Pandas Dataframe Some Row Appers