Having an issue running my python program in VS Code using open() - python

I am writing a Python program which reads data from a .txt file and writes to it. I am using VS Code as my editor and I am coming across an error where it doesn't recognize infile = open("poem.txt", "r") and tells me there is no such file or directory poem.txt. I can assure you it does exist and it is in the same folder. I can open the same program within IDLE and it runs fine. Is there a way to correct this error for VS Code without trying to hard code in absolute path for the file?

This code is not hardcoded, but will change with the directory the program is run from:
Join constructs file paths from arguments, and getcwd gets the current working directory.
import os
infile = open(os.join(os.getcwd(), "poem.txt"), "r")

Related

Forced to enter full pathname every time instead of just file name

Every time I try to do an action such as running a program in the VScode Terminal (also happens in PyCharm) I have to enter in the full pathname instead of just the file name. For example, instead of just doing python3 test.py to run a program, I have to enter in python3 /Users/syedrishad/Desktop/Code/test.py.
Now, this is annoying and all but it doesn't bother me too much. What does bother me is when my program is trying to pull/ open files from somewhere else. If I wanted an image call Apple.jpeg, instead of just typing in Apple.jpeg, I'd have to go and find the full pathname for it. If I were to upload a piece of code doing this to someplace like GitHub, the person who'd want to test this code out for themselves will have to go in and replace each pathname with just the file name or it won't work on their computer. This problem has been going on for a while, and I sadly haven't found a solution to this. I would appreciate any help I get. I'm also on a Mac if that makes a difference.
You could use os and sys that gives you the full path to the folder of the python file.
Sys gives you the path and os gives you the possibility to merge it with the file name.
import sys, os
print(sys.path[0]) # that is the path to the directory of the python file
print(sys.path[0]+'/name.txt') #full path to the file
print(os.path.join(sys.path[0],'name.txt')) # os.path.join takes two parameters and merges them as one path using / but the line above is also fine
In VS Code, its internal terminal is in the currently opened project folder by default. Therefore, when you use the command "python file_name.py" to run the file, the terminal cannot find the file that exists in the inner folder.
Therefore, in addition to using the file path, we can also add related settings to help it find the file.
Run: When using the run button to execute the file, we can add the following settings in "settings.json", it will automatically enter the parent folder of the executed file.
"python.terminal.executeInFileDir": true,
"When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder."
debug: For debugging code, we need to add the following settings in "launch.json":
"cwd": "${fileDirname}",

Python script can't find file anymore after packing with pyarmor/pyinstaller as unix executable on Mac

My problem is that when I pack my .py script with either pyarmor or pyinstaller the script can't find my files anymore. I am using this code to read a file:
with open('./file.txt', "r") as textfile:
textdata = textfile.read()
print(textdata)
I found out that the script uses /Users/{username} as absolute file path which is my problem. Because no matter where the file is started it always uses this /Users/{username} path. I even tried getting the file path with:
workingpath = str(Path().absolute())
But even that returns /Users/{username}. Is there any solution to this problem?
Thanks in advance for any help.

Set Python script as default for opening file type

I am trying to set my Python script as default program to open a file (e.g. open every .txt file with my program when I double click on it).
I already tried this:
from sys import argv
# write the arguments to a file for debugging purposes
with open("output.txt", "w+") as f:
f.write(repr(argv))
I converted the script into a .exe with pyinstaller, otherwise Windows won't let me use it to open files.
In the command prompt, it works: typing main.exe some args indeed yields an output.txt file, with inside it ["C:\...\main.exe", "some", "args"].
I was hoping that by opening a .txt file with this script (in File Explorer > right click on file > open with > more apps > check "always use this app" and selecting the executable), it would be the same as running main.exe C:\...\that_file_that_i_just_clicked.txt in the command prompt, from which I could then use the file path to open it in my program. However, this does not happen. In fact, main.exe never even gets executed (because it doesn't even create a new output.txt).
How can I link a pyinstaller-generated executable to always open a filetype, and how do I then know the path of the opened file in Python?
The thing that I was doing wrong, was creating output.txt using a relative file path. Since the script was converted into an .exe (which basically wraps the interpreter and the script into a single file), the relative file path stopped working.
Using an absolute file path fixed my issue (as pointed out by Eryk Sun).

File sharing problem with Python inside Excel

I have python 2.6 script that creates a bunch of csv files on windows.
This script can be run stand alone or inside Excel via VBA shell command.
There are no problems when runs as stand alone, followed by VBA script.
When I run script inside Excel with a shell call. I have file sharing problems.
The Script creates runs, close files
fw = open(fn, "wb")
fw.write(....)
fw.close()
at the end of script I have:
os._exit(1)
Then Excel VBA does its stuff with the files. This gives error messages.
The error msg:
"FILE Now Available"
....is now avaiable for editing.
Choose read-write to open it for editing.
The script is multitheaded....
You may want to create a delay after the shell call (doEvents or sleep(100) might work) to allow the OS to properly close the file and remove all pointers to the file.

Python : get all exe files in current directory and run them?

First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner
What I need exactly is :
a *.bat file that will run the script
a python script that will :
get all *_test.exe files in the current working directory
run all the files which were the result of the search
Best regards
import glob, os
def solution():
for fn in glob.glob("*_text.exe"):
os.startfile(fn)
If you copy this into a file, the script should do as you asked.
import os # Access the operating system.
def solution(): # Create a function for later.
for name in os.listdir(os.getcwd()):
if name.lower().endswith('_test.exe'):
os.startfile(name)
solution() # Execute this inside the CWD.

Categories

Resources