Katy shares her tech knowledge and research with anyone who wants to learn the smartest way to use technology.
Handling Files in Python
Here are some suggested approaches for opening and creating files in Python:
- Check if file exists: path.exists('file')
- Check if file exists and create it if not: open('file',"a")
- Create a File If It Doesn't Already Exist: try, catch with path.exists('file')
Check If File Exists (Simple Method)
To check if a file exists using Python you can use path.exists() and pass it the name of your file as a string.
This command simply checks whether a file exists on your file system. It assumes you already have the os module imported by using import os.
Check If File Exists, Create If Not with open()
To check if a file exists and create it if it doesn't already exist you can use the command open() with a "a" parameter. Pass in the name of the file you want as a string.
The “open” function with an “a” parameter basically forces the file to open, whether it's already there or not. After this line, you know you have a file open with that name.
This is a good approach if your program needs to create a log file or data file that might already exist. The program could have been run before and the file already exists and if it does you need to open it to write more to it. If it doesn’t exist then you’ll need to create it.
Only Create a New File If It Doesn’t Already Exist
If you need the capability to only create a file if one with that name doesn’t already exist, you need to use a try except statement.
Try/Except Statement Basics
If you haven't used a try/except statement in programming before, it's a really useful piece of logic. The "try" keyword tells the compiler to attempt everything in that section. If any line would cause an error it skips down to the "except" section. So in use, lines in the try statement don't have to be executable and lines in the except statement are only run if any of the "try" lines fail.
A common use for a try, except setup is to "catch" any errors and write them to log but continue executing the program.
Creating A File with Try/Except Method
You might pick this approach for a program that shouldn't overwrite an existing file. Putting the write command in the "except" part of the statement ensures only new files are created.
Here are some other Python commands you might find useful in file handling:
- os.path.isfile() - returns True if path is to a file
- os.rename() - changes the name of a file
- f.write('string') - writes to the file, where f is the file handle
- f.close() - closes the file, where f is the file handle
Share in the Comments
Are you having trouble handling files in Python? Or do you have a new approach you use? Please share with the community in the comments below.
© 2019 Katy Medium