Manipulating files
Hey there! Welcome back to the Python basics tutorial. Today we'll start to do some fun stuff, like manipulating files.
Let's say you have a text file with data. You want to read the text file and print it to the console. For that, we'll have to use the open
function.
Setting up the files
First of all, create a new directory/folder and create a Python file inside it called test.py
or anything else you would like to to be, just make sure it ends with .py
. Now, make another file called test.txt
and put the following text inside it:
Now, open the Python file and type this:
Done. We've opened a file. We're passing two arguments to open
: The path to the file we're opening, and the mode we want to open it in. A quick list of the modes:
r
- Read mode ( To read plaintext files)
w
- Write mode (To write to files)
a
- Append mode (To add more text to the end of a file)
rb
- Read Binary mode (To read binary files like images, videos, audio etc)
wb
- Write Binary mode (To write to binary files)
ab
- Append Binary mode (To add more binary to the end of a file)
We can use full paths too, such as D:\\testfolder\hello.txt
in Windows or /home/harrypotter/Documents/hello.txt
in *nix systems (Mac and Linux). Or relative paths ../hello.txt
to get a file named hello.txt
in the parent directory.
OK, now we try to read from the file. Edit the Python file now:
Run, and you should see Hell is empty and all the devils are here.
being printed to the console. It's good practice to close a file after you're done working with it:
Now, to write to a file:
Done. Now if you open the file with a text editor you should see the new text inside.
Opening in write mode completely overwrites the file, whether you write anything or not.
Let's try append
mode to keep the current text and add some more to the end.
Auto closing files
If you feel that the method above is too verbose you can:
This automatically closes the file.
The with
method is the recommended way of opening files.
OK. Now we know how to manipulate files. You can now do all sorts of cool stuff. I'd say you've learned 75% of Python basics.
Last updated
Was this helpful?