Need help to open a file in python - python

I don't know what's wrong here, all I'm trying to do is to open this file, but it says it can't find such a file or directory, however as I have highlighted on the side, the file is right there. I just want to open it. I have opened files before but never encountered this. I must have missed something, I checked online, and seems like my syntax is correct, but I don't know.
I get the same error when I try with "alphabetical_words" which is just a text file.

When open() function receives a relative path, it looks for that file relative to the current working directory. In other words: relative to the current directory from where the script is run. This can be any arbitrary location.
I guess what you want to do is look for alphabetical.csv file relative to the script location. To do that use the following formula:
from pathlib import Path
# Get directory of this script
THIS_DIR = Path(__file__).absolute().parent
# Get path of CSV file relative to the directory of this script
CSV_PATH = THIS_DIR.joinpath("alphabetical.csv")
# Open the CSV file using a with-block
with CSV_PATH.open(encoding="utf-8") as csvfile:
pass # Do stuff with opened file

You need to import csv. Then you can open the file as a csv file. For example,
with open ("alphabetical.csv", "r") as csvfile:
Then you can use the file.
Make sure the file is in your cwd.

Related

Unable to find text file

I am new to VSCODE. I opened a text file via vscode and entered some details. Where can I find the file?
f=open('story.txt','w')
f.write('my name is')
f.write('my age is')
f.close()
f=open('story.txt', 'r')
print(f.readline())
f.close()
this is the output
However I cannot find 'story.txt' in file explorer. I used another text editor and then error came as file not found. but when i reopened the file in vs code I was getting a proper output.
From the screenshot you supplied it looks like you are running the script from C:\Users\<YourName>, then this is where your story.txt file will be.
To specify another location you need to supply the open() method with a full path
Also, it's best practice to close the file before opening it again for reading. also, you might want to use a context manager to help you with this
If you want your file saved in the directory of your script, you can use os and __file__ to locate your script's directory and use that.
import os
my_dir = os.path.dirname(__file__)
new_path = os.path.join(my_dir, 'story.txt')
print(new_path)
os documentation
__file__ explained
When you run python script it will execute from the current working directory by defaut.
If you want to be sure where your file will be, you may pass the complete file path instead of file name only (eg: C:\\filepath\\filename.txt)
or you can move to the desired directory before read/write with os.chdir(filepath)
If you don't know where the script is running you can use os.getcwd() to get this directory from your code
import os
print(os.getcwd()) #will show the current working directory
os.chdir("c:\\") #will move to C:\ directory
f=open('story.txt','w')
f.write('my name is')
f.write('my age is')
f=open('story.txt', 'r')
print(f.readline())
f.close()
When you create a file with Python, the file will be create in the same folder as your script. So, if your folder all_python_scripts contains your script, your file story.txt will be created in this folder. Try to search your file in the script's folder.

Importing DataFrames - no such file or directory

I am trying to import a csv file as a dataframe into a Jupyter notebook.
rest_relation = pd.read_csv('store_id_relation.csv', delimiter=',')
But I get this error
FileNotFoundError: [Errno 2] No such file or directory: 'store_id_relation.csv'
The store_id_relation.csv is definitely in the data folder, and I have tried adding data\ to the file location but I get the same error. Whats going wrong here?
Using the filename only works if the file is located in the current working directory. You can check the current working directory using os.getcwd().
import os
current_directory = os.getcwd()
print(current_directory)
One way you can make your code work is to change the working directory to the one where the file is located.
os.chdir("Path to wherever your file is located")
Or you can substitute the filename with the full path to the file. The full path would look something like C:\Users\Documents\store_id_relation.csv.
Always try to pass the full path whenever possible
By default, read_csv looks for the file in the current working directory
Provide the full path to the read_csv function
However in your case , data and Data are different , and file paths are case sensitive
You can try the below path to fetch the file and convert it into a dataframe
rest_relation = pd.read_csv('Data\\store_id_relation.csv', delimiter=',')
In case where you don't want to change your read_csv()'s parameter, just make sure you are in a correct path of directory which your .csv file is in. Otherwise you can change your directory into there and then run the python file or simply change read_csv()'s parameter.

Importing a file using pandas

Data visualisation: I want to import a file using pandas. I assigned a variable and file name given is correct but it shows a error message as file does not exist
Code: sample_data = pd.read_csv('sample_data.csv')
You're probably in the wrong working directory. Run os.getcwd() to check. If so, you can either change working directories with os.chdir() or give an absolute path to the file instead of a relative path.
If you're already in the right working directory, run os.listdir() to make sure the file is actually there.
Ok, in this case, what you will have to do is get the path file by right-clicking on the file and going to properties(Windows, don't know about Mac). Then just copy the file path and paste it instead of the file name. So for now, it should be something like this(as I don't know your file path):
sample_data = pd.read_csv('C:\Users\SVISHWANATH\Downloads\datasets')
Now, after the last folder, give in your file name. So now, it should look like this:
sample_data = pd.read_csv('C:\Users\SVISHWANATH\Downloads\datasets\sample_data.csv')
However, this will still not work as the slashes need to be the other way. Because of this, there will have to be an r before the quotes.
sample_data = pd.read_csv(r'C:\Users\SVISHWANATH\Downloads\datasets\sample_data.csv')
Now this should work as all the requirements are met.
You need to store the .csv file in a folder where the actual program is stored, otherwise you have to give a proper path to the file:
sample_data = pd.read_csv('filepath')

How to open a specific path with open()?

I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
I assume you're opening files with:
open("filename","r")
If you do not provide an absolute path, the open function will always default to a relative path. So, if I wanted to open a file such as /mnt/storage/dnd/5th_edition.txt, I would have to use:
open("/mnt/storage/dnd/4p5_edition","r")
And if I wanted to copy this file to /mnt/storage/trash/ I would have to use the absolute path as well:
open("/mnt/storage/trash/4p5_edition","w")
If instead, I decided to use this:
open("mnt/storage/trash/4p5_edition","w")
Then I would get an IOError if there wasn't a directory named mnt with the directories storage/trash in my present folder. If those folders did exist in my present folder, then it would end up in /whatever/the/path/is/to/my/current/directory/mnt/storage/trash/4p5_edition, rather than /mnt/storage/trash/4p5_edition.
since you said that the file will be placed in the same path where the program is, the following code might work
import os
filename = "name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
Its pretty simple just get the path from user
subpath = raw_input("File path = ")
print subpath
file=open(subpath+str(file_name),'w+')
file.write(content)
file.close()
I think thats all you need let me know if you need something else.
like you say, the file should be in the same folder of the project so you have to replace it, or to define a function that return the right file path into your open() function, It's a way that you can use to reduce the time of searching a solution to your problem brother.
It should be something like :
import os
filename = "the_full_path_of_the_fil/name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
then you can use the value of the f variable as a path to the directory of where the file is in.

How to open a video file in python 2.7?

I am new to python, and I am trying to open a video file "This is the file.mp4" and then read the bytes from that file. I know I should be using open(filename, "rb"), however I am not clear about the following things:
In what directory is python looking for my file when I use open()? (My file is located in the downloads folder, should I move it? Where?
Is using "rb" the correct way to read the bytes from a file?
So far I tried to open the file and I get this error:
IOError: [Errno 2] No such file or directory: 'This is the file.mp4'
I know it is probably an obvious thing to do, however I have looked all over the internet and I still haven't found an answer.
Thank you in advance!
By default, Python opens the file from the current working directory, which is usually the folder where the .py script of the program is located.
If you move the video file in the same directory as the script, it should work.
You can also view the current working directory like this:
import os
print os.getcwd()
Also, instead of moving the file, you can just change "This is the file.mp4" to "C:/Users/<username>/Downloads/This is the file.mp4" if you are using Windows 7 and maybe 8. You will have to change the <username> to your computer username.
Wildcards might also work: "~/Downloads/This is the file.mp4"
Finally, what are you planning to do with the video file bytes? If you want to copy the file to somewhere else, there are modules to do that.
"rb" is a correct way to read bytes of a file.

Categories