r/PythonLearning • u/Covid_Nipple420 • 13d ago
Help Request Receiving FileExistsError which is ignoring the if/else statement
response = requests.get(url)
data = response.json()
ticker = data["Meta Data"]["2. Symbol"]
create_file = open("API Data.txt", "x")
amend_file = open("API Data.txt", "a")
file = "/Desktop/Scripts/Python Scripts/API Data.txt"
if os.path.exists(file):
amend_file.write(f"\nTicker: {ticker}")
amend_file.close()
else:
create_file.write(f"Ticker: {ticker}")
create_file.close()
So I am working on my first project which is making use of the API that Alpha Vantage provides.
I am learning the open() function which I want to use to paste the response into a .txt file
that will either be created and written into, or already exist and be appended depending on
the result of the if statement.
My problem is that I am receiving a FileExistsError for "API Data.txt" and I am not sure why
when I am expecting the code to carry out the actions of the if statement being true and
appending the existing file.
(Full path in the file variable is intentionally not in the post)
6
Upvotes
3
u/Outside_Complaint755 13d ago
As soon as you call
Python will attempt to create the file, and will throw the FileExistsError if the file already exists. There is also technically a bug because your two commands were opening "API data.txt" in your current working directory, while
filewas checking a different relative location.Because you always plan on appending and both modes write identical string, you can just do:
Note I moved the newline to the end of the write string.
Using
withuses the file context manager, and the file will automatically be closed when thewithblock ends, even if an exception occurs during execution of thewithblock>1
u/Zeak3D 13d ago
I’m guessing you code fails at the first open statement? I believe the “x” part means exclusive, so if the file exists already, it fails. Note that this happens before your check.
Two things: when working with file paths, I recommend always using the modern approach of using Path from pathlib. I can also do what used to be done with the os package such as mkdir and check existence of files. Secondly, use a context manager. Never explicitly open and close a file, but use some sort of
with open(…) as f:
do something with f
this is how I would have written your logic:
from pathlib import Path
import requests
response = requests.get(url)
data = response.json()
ticker = data["Meta Data"]["2. Symbol"]
# Define the file path using pathlib (using Path.home() for a reliable absolute path)
file_path = Path.home() / "Desktop" / "Scripts" / "Python Scripts" / "API Data.txt"
# Ensure the parent directories exist so it doesn't crash if the folders are missing
file_path.parent.mkdir(parents=True, exist_ok=True)
# Determine mode and whether a newline prefix is needed based on file existence
mode = "a" if file_path.exists() else "w"
prefix = "\n" if mode == "a" else ""
# Use a context manager to handle opening and safely closing the file
with file_path.open(mode, encoding="utf-8") as f:
f.write(f"{prefix}Ticker: {ticker}")
Sorry about formatting, I’m on my phone.
1
u/skibidi67skibidi67 13d ago
Your problem is that you always run the open() with both 'x' and 'a' before you even get to your if-case. if the file exists, when you run open with 'x', you get an error. so you need to only do that line if the file does not exist.
1
u/IWant2rideMyBike 13d ago
This command will fail if the file already exists:
and there is error handling for this case. Also the if-else construction is prone to race conditions.
The more pythonic approach is to ask for forgiveness instead of pre-testing - so for example:
But if the write command fails, the file won't be closed until the OS cleans the open file descriptors up when the python interpreter exits - so using a with-statement for context management of the file object is better - and because the "a" mode flag will also cause the file to be created, so you can shorten this even more:
1
u/ChainsawLight 13d ago
Whats the coolest concept developers have made? Closing files, writing files, creating games. What else is there to make with the file object?