Unable to find text file - python

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.

Related

Need help to open a file in 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.

Folders in VS code

If I have a .py (called p.py) folder where I have my code and I want to open a file which is a .json (called j.json) file and I have opened it as a folder next to the p.py folder. I want to read from the j.json make it a dictionary. It does not seem to work with this :
import json
with open("j.json") as f:
data = json.load(f)
output: FileNotFoundError: [Errno 2] No such file or directory
What am I doing wrong?
If p.py and j.json are at the same level, we can directly quote it as its name instead of its absolute path:
Turn to file explorer, View -> Select File name extensions, to check if the name of j.json is right, or we can say, to check if j.json exists:
Try the full path directory instead of just your file name. But you should put an r before the string. E.g.
with open(r'path_to_file/j.json') as f:
data = json.load(f)
When you specify a path (that is not absolute) it is relative to the directory you are executing Python in
Let's say I'm in my Terminal at directory C:/Users/Mathias/Desktop and I execute the following code with Python
with open("veryimportant.json", "r") as file:
for line in file:
print(line)
"veryimportant.json" will be relative to my working directory (C:/Users/Mathias/Desktop) so the absolute path will be C:/Users/Mathias/Desktop/veryimportant.json
So what can you do?
You have the following options.
Option 1
Move the j.json file to the same directory as your p.py file
Option 2
Refer to j.json with the absolute path (looks something like this "C:/path/to/file.json" with your drive letter first)

Regarding file io in Python

I mistakenly, typed the following code:
f = open('\TestFiles\'sample.txt', 'w')
f.write('I just wrote this line')
f.close()
I ran this code and even though I have mistakenly typed the above code, it is however a valid code because the second backslash ignores the single-quote and what I should get, according to my knowledge is a .txt file named "\TestFiles'sample" in my project folder. However when I navigated to the project folder, I could not find a file there.
However, if I do the same thing with a different filename for example. Like,
f = open('sample1.txt', 'w')
f.write('test')
f.close()
I find the 'sample.txt' file created in my folder. Is there a reason for the file to not being created even though the first code was valid according to my knowledge?
Also is there a way to mention a file relative to my project folder rather than mentioning the absolute path to a file? (For example I want to create a file called 'sample.txt' in a folder called 'TestFiles' inside my project folder. So without mentioning the absolute path to TestFiles folder, is there a way to mention the path to TestFiles folder relative to the project folder in Python when opening files?)
I am a beginner in Python and I hope someone could help me.
Thank you.
What you're looking for are relative paths, long story short, if you want to create a file called 'sample.txt' in a folder 'TestFiles' inside your project folder, you can do:
import os
f = open(os.path.join('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()
Or using the more recent pathlib module:
from pathlib import Path
f = open(Path('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()
But you need to keep in mind that it depends on where you started your Python interpreter (which is probably why you're not able to find "\TestFiles'sample" in your project folder, it's created elsewhere), to make sure everything works fine, you can do something like this instead:
from pathlib import Path
sample_path = Path(Path(__file__).parent, 'TestFiles', 'sample1.txt')
with open(sample_path, "w") as f:
f.write('test')
By using a [context manager]{https://book.pythontips.com/en/latest/context_managers.html} you can avoid using f.close()
When you create a file you can specify either an absolute filename or a relative filename.
If you start the file path with '\' (on Win) or '/' it will be an absolute path. So in your first case you specified an absolute path, which is in fact:
from pathlib import Path
Path('\Testfile\'sample.txt').absolute()
WindowsPath("C:/Testfile'sample.txt")
Whenever you run some code in python, the relative paths that will be generate will be composed by your current folder, which is the folder from which you started the python interpreter, which you can check with:
import os
os.getcwd()
and the relative path that you added afterwards, so if you specify:
Path('Testfiles\sample.txt').absolute()
WindowsPath('C:/Users/user/Testfiles/sample.txt')
In general I suggest you use pathlib to handle paths. That makes it safer and cross platform. For example let's say that your scrip is under:
project
src
script.py
testfiles
and you want to store/read a file in project/testfiles. What you can do is get the path for script.py with __file__ and build the path to project/testfiles
from pathlib import Path
src_path = Path(__file__)
testfiles_path = src_path.parent / 'testfiles'
sample_fname = testfiles_path / 'sample.txt'
with sample_fname.open('w') as f:
f.write('yo')
As I am running the first code example in vscode, I'm getting a warning
Anomalous backslash in string: '\T'. String constant might be missing an r prefix.
And when I am running the file, it is also creating a file with the name \TestFiles'sample.txt. And it is being created in the same directory where the .py file is.
now, if your working tree is like this:
project_folder
-testfiles
-sample.txt
-something.py
then you can just say: open("testfiles//hello.txt")
I hope you find it helpful.

Accessing text files out of python directory

I am doing a project using python in which I got stuck at a point where I want to access some text files which are saved outside the project directory.
The path where my text files are saved:
C:\Users\saqibshakeel035\Desktop\Scientific Project Lithim battery project\text_file_r_w
The path of my python project:
C:\Users\saqibshakeel035\PycharmProjects\Tutorial_1
I want to open/read my text files (external > not included in python project folder)
I already know the Reading/writing etc etc within the same folder where the python project .py file is present but struggling with the different paths.
I tried:
import os
from os import path
print("Your cunrrent directory is : %s" %path.curdir)
strpath = r"C:\Users\saqibshakeel035\Desktop\Scientific Project Lithim battery project\text_file_r_w"
print("Your current directory is %s: " %path.dirname(strpath))
print("Your current directory is : %s" %path.abspath(strpath))
This works fine and it shows my abspath where my text files are stored but when I try to read it with the following command
f = open("file1.txt","r")
It gives error that no such directory or file found
I suggest you try f = open("C:/text/to/path/file1.txt","r") or the code #Jaba has mention. Either works fine
Can you try using the full path to "file1.txt" in the open function.
f = open("Full_path_to_file1.txt", "r")
Another option is to change the current directory,
os.chdir(path)

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.

Categories