So currently I'm practicing Python and I have this line of code:
print(f"{someList}", file=open("generatedList.txt", "w"))
When I tried to run it on Notepad++ using a run command of python "$(FULL_CURRENT_PATH)", it doesn't generates the .txt file but in the Notepad++ folder. When I tried to run exactly the same code to the IDLE it generates the .txt file on the working folder.
Why is that? Should I change something to the run command? I prefer Notepad++ as a text editor.
Btw, I'm using Python 3.8.5
So I don't know if it is okay but I think I know now how to make it save on wherever directory you want I just experimented and tried it out.
from this code :
print(f"{flippedCoins}", file=open("generatedFlips.txt", "w"))
You'll just need to add the directory where would like to save it!
print(f"{flippedCoins}", file=open("C:\The\Directory\You\Want\to\Save\it\generatedFlips.txt", "w"))
You can use the __file__ variable to retrieve the location of the script, and use that to construct an absolute path for your output file:
import os.path
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
FILE_PATH = os.path.join(SCRIPT_DIR, "generatedList.txt")
...
with open(FILE_PATH, "w") as fh:
print(f"{someList}", file=fh)
If you prefer to work with local file paths, you could change the working directory to the one where you want to dump the file:
import os
os.chdir("c:/path/to/some/directory")
If you can't locate the output file when launching the script from and IDE and want to figure out what the script's working directory is, you can print it:
import os
print(os.getcwd())
You can always provide an absolute path to the file, wherever the script is executed from:
with open("c:/path/to/some/file.txt", "w") as fh:
print(f"{someList}", file=fh)
Related
Opening and loading data from a file that is situated in the same folder as the currently executing Python 3.x script can be done like this:
import os
mydata_path = os.path.join(os.path.dirname(__file__), "mydata.txt")
with open(mydata_path, 'r') as file:
data = file.read()
However once the script and mydata.txt files become part of a Python package this is not as straight forward anymore. I have managed to do this using a concoction of functions from the pkg_resources module such as resource_exists(), resource_listdir(), resource_isdir() and resource_string(). I won't put my code here because it is horrible and broken (but it sort of works).
Anyhow my question is; is there no way to manage the loading of a file in the same folder as the currently executing Python script that works regardles of wether the files are in a package or not?
You can use importlib.resources.read_text in order to read a file that's located relative to a package:
from importlib.resources import read_text
data = read_text('mypkg.foo', 'mydata.txt')
So if I open a folder in vs code that stores the files or modules I need to open or import, my code works fine, however if I open a folder higher in the directory, I get errors such as file not found.
Path: C:\Users\user1\Desktop\Programming\Python\30DaysPython\Day10
My .py file is in Day10, if I open VS code in that folder my program works, but if I open VS in 30DayPython, it doesn't work.
Why do I have to open vs in the folder that I am working on (containing my files), shouldn't it use the relative path of the file I am running and not where I open vs code from?
My code:
import os
email_txt = os.path.join('templates', 'email.txt')
content = ''
with open(email_txt, 'r') as f:
enter code herecontent = f.read()
print(content.format(name='Joe'))
Image of opening vs code in 1 folder higher than the folder that contains the program and it doesn't work.
That's because your current working directory changed. When you open 30DaysPython as current folder, you have to change the path code to
email_txt = os.path.join('Day10\\templates', 'email.txt')
Then the error should go away.
When i run in terminal i get the [Errno 2] No such file or directory error, but when i use debug mode it works.
the error occurs here,
list = open(filename, "r")
the code also works with IDLE
Your debugger is most likely running in a different location than your terminal. cd your terminal to where the file is located, or try using the absolute path instead of a relative one.
If you add these few lines in your code and run it using your IDE or Terminal, you'll notice the difference:
import os
curdir = os.getcwd()
print('My current directory is {}'.format(curdir))
fullpath_to_filename = os.path.join(curdir, filename)
print('When I run `open(filename)`, python sees: {}'.format(fullpath_to_filename))
print('This filepath is {}valid'.format('' if os.path.exists(fullpath_to_filename) else 'not '))
You'll likely experience something similar to below:
# on IDE:
My current directory is c:\Users\me\Projects\
When I run `open(filename)`, python sees: c:\Users\me\Projects\test.txt
This filepath is valid
# on Terminal:
My current directory is c:\Programs\Python38\
When I run `open(filename)`, python sees: c:\Programs\Python38\test.txt
This filepath is not valid
Solution: use absolute path for your filename, or os.chdir(...) to the correct parent path before location filename. I would recommend the former to avoid managing directories.
Got some weird behavior here. Basically I am using import os to find the path of the exe file and then I use that path in a batch file to move the exe file. I've also used pyinstaller to make the program an exe.
Now here is where the issue occurs. The os commands works well, but it thinks the file is still a .py
This is really odd because I made this variable:
dirName = os.path.abspath(__file__)
Now, this finds the correct directory and the correct file name(but not file type)
Then I use that variable to write down which directory the file is currently in like this:
move.write('move /Y "' + str(dirName) + '" (code continues here, but not important)
This works when the file is a .py but not when it is a .exe
I hope this makes sense, feel free to ask and/or edit if anything is unclear.
Current output: The system cannot find the file specified.
Wanted output: 1 file(s) moved.
You can specify the extension you want by this way:
files = os.listdir('/your/directory')
for filename in files:
if filename.endswith(".exe"):#or extension you want
#copy file you want
I'm trying to open a file in python. Simple enough. The script that I am using is the same directory as my code, so I just use
myfile = open('file.txt', 'r')
This worked fine before, but now I am getting the error 'No such file or directory' (Errno2)
Why is this happening? I've used OS to check if I am in the right directory, and it is fine. What is python doing differently now than it did 20 minutes ago, when it found the file perfectly??
Assuming the file you are trying to open/read has appropriate permissions, the behavior is defined based on how you are invoking your python program. Let's assume your code and the file.txt are in ~/Desktop
If you are in ~/Desktop and do a python code.py your code will work fine. But if you are in say your home folder - ~ and do a python ~/Desktop/code.py then the python interpreter assumes your current working directory to be ~ and will return the error:
IOError: [Errno 2] No such file or directory: 'file.txt'
since it will not find file.txt in ~
Further, in the context of the given example:
os.getcwd()
returns the absolute path of your home directory and
os.path.realpath(__file__)
returns the absolute path of your python source file
Is it possible you are typing the name wrong, eg "test.fna" versus "test.fna.txt"?