This question already has answers here:
How does using the try statement avoid a race condition?
(3 answers)
Closed 8 years ago.
I would like to know how I could check to see if a file exist based on user input and if it does not, then i would like to create one.
so I would have something like:
file_name = input('what is the file name? ')
then I would like to check to see if file name exist.
If file name does exist, open file to write or read, if file name does not exist, create the file based on user input.
I know the very basic about files but not how to use user input to check or create a file.
if the file is not a file :(return False)
import os.path
if not os.path.isFile(file_name):
print("The File s% it's not created "%file_name)
os.touch(file_name)
print("The file s% has been Created ..."%file_name)
And you can write a simple code based on (try,Except):
try:
my_file = open(file_name)
except IOError:
os.touch(file_name)
To do exactly what you asked:
You're going to want to look at the os.path.isfile() function, and then the open() function (passing your variable as the argument).
However, as noted by #LukasGraf, this is generally considered less than ideal because it introduces a race condition if something else were you create the file in the time between when you check to see if it exists and when you go to open it.
Instead, the usual preferred method is to just try and open it, and catch the exception that's generated if you can't:
try:
my_file = open(file_name)
except IOError:
# file couldn't be opened, perhaps you need to create it
Related
This question already has answers here:
How do I raise a FileNotFoundError properly?
(2 answers)
Closed 1 year ago.
I would like to have a check for save games for a command-line game I'm working on.
The save games are singular ".txt" files, and the way this short piece of code works is it tries to open the "name.txt" file in the "%appdata%\Roaming\AdventureChapt1\" folder, then looks for an error message when Python can't find the file.
How would I do this?
print('Loading Save Data')
savecheck = open('%appdata%/Roaming/AdventureChapt1/name.txt', 'rt')
if savecheck.read() == '':
newgame() # calls the "newgame" function to bring up the New Game wizard
You can use try and except
try:
with open('%appdata%/Roaming/AdventureChapt1/name.txt', 'rt') as savecheck:
# code that reads saved game
except FileNotFoundError:
newgame()
You can use a variety of things to see if the file exists or not.
My flavour is
from os import path
filepath = "path_to_file"
if not path.exists(filepath):
# do stuff when file doesn't exist
ref: https://www.guru99.com/python-check-if-file-exists.html
This question already has answers here:
Understanding the Python 'with' statement
(5 answers)
Closed 4 years ago.
I am using python 2.x and I am going through company code, I found code that looks like:
filename = open('text.json', 'r')
# doSomething()
filename.close()
I am used to reading a file like so:
with open('text.json', 'r') as filename
# doSomething()
Can anyone explain what the difference is?
The second one is usually used with a context manager, so you can do
with open('text.json', 'r') as filename:
#your code
And you can access the file using the filename alias.
The benefit of that is that the context manager closes the file for you.
If you do manually as your first example you would need to manually call filename.close() after you used it to avoid file locking
When you open a file in python, you have to remember to close it when you're done.
So with your 1st line:
filename = open('text.json', 'r')
You'll need to remember to close the file.
The second version you have is typically used like this:
with open('text.json', 'r') as filename:
#block of code
This will automatically close the file after the block of code is run.
The other difference is the way you're naming the file object as "filename". You end up with the same object in both, just naming it in two different ways.
I am working on a .txt file. But there are 2 conditions. I do not know which one will occur. It depends on the user's decision.
My program will write what the user will make, but if there is no such a file in my program will have to create a file which its name what the user enter on the command line. Nevertheless, if there is a file my program will make all operation over this file.
So, I have tried a+ command like file = open(sys.argv[1],"a+") but this did not work well. It has created a new file it didn't exist. But it did not read my file which already exists. Do you think how can I open the file that works with two conditions?
You want to use a try statement. Something like:
try:
# Try to open the file
file = open(sys.argv[1], "r")
except FileNotFoundError:
# If the file does not exist, create it
file = open(sys.argv[1],"a+")
I forgot how many times I opened the file but I need to close them I added the txt.close and txt_again.close after I opened it at least 2 times
I'm following Zed A. Shaw Learn Python The Hard Way
#imports argv library from system package
from sys import argv
#sets Variable name/how you will access it
script, filename = argv
#opens the given file from the terminal
txt = open(filename)
#prints out the file name that was given in the terminal
print "Here's your file %r:" % filename
#prints out the text from the given file
print txt.read()
txt.close()
#prefered method
#you input which file you want to open and read
print "Type the filename again:"
#gets the name of the file from the user
file_again = raw_input("> ")
#opens the file given by the user
txt_again = open(file_again)
#prints the file given by the user
print txt_again.read()
txt_again.close()
In order to prevent such things, it is better to always open the file using Context Manager with like:
with open(my_file) as f:
# do something on file object `f`
This way you need not to worry about closing it explicitly.
Advantages:
In case of exception raised within with, Python will take care of closing the file.
No need to explicitly mention the close().
Much more readable in knowing the scope/usage of opened file.
Refer: PEP 343 -- The "with" Statement. Also check Trying to understand python with statement and context managers to know more about them.
I need to search a directory for all files staring with downtime and add a line into each one.
Right now I have the following:
os.chdir("/misc/downtimerecords")
for file in glob.glob("downtime*"):
fo=open("","a+")
fo.write("Network Cause")
fo.close()
How can I change this so that no matter how many files I have in the directory this will work? Currently I will get an error because of the "" in fo=open. I want this to be the name of every file that begins with downtime.
Better still:
stringvar = "string to append"
for filename in glob.glob("downtime*"):
with open(filename,"a+") as fo:
fo.write("Network Cause {}\n".format(stringvar))
...as file shadows a Python built-in
The with open(...) as ... : idiom ensures that the file object gets closed even if something nasty happens (and it's neater!)
Replace the "" in open() with file. When you use a for loop to iterate over a list in python, the variable after for is the variable where you can access the current element of the list.