Python Tutorial File Handling In Python

Helpful?


  • Total voters
    1

Tretabyte

New Coder
Apr 8, 2019
24
13
4
Welcome back!
I haven't done a tutorial in a while, so I thought I'd do one on a topic that I see some people struggle with.
File I/O handling.

Let's get started then.

First of all you need to know how to actually define that file and open it.

test_file = open("myfile.txt","r")
The line above opens a file (if found) called "myfile.txt" as a read-only.

There are many modes to open a file as, write, read, readwrite and more.

I will list a few:
  • r - Read Only
  • r+ - Read and Write

  • w - Write only, also creates a new file if it doesn't exist
  • w+ - Read and Write

  • a - Appending, also creates a new file if it doesn't exist
  • a+ - Appending and reading

file = open("filename.txt","mode")

mode can be any of the ones in the list and a few more which I will not go into detail on.

Now that you've opened the file you need to know how to close the file so that you do not have a file open in the background the whole time the program is running.
To do so you simple run:
file.close()

Okay, great, you can open and close a file.
But what now?
Well, you can also read, write and append onto the end of that file. And if you add some modules you can sort through folders, delete files, create folders, and much more but I will go into that on another tutorial.

So, writing to a file,
There are multiple ways to write to a file, writelines and write.

file.write("THIS IS ON ONE LINE")
file.write("THIS IS ON THE SAME LINE")
file.write("\n THIS IS ON A SEPERATE LINE")

Python:
file = open("FileName.txt","w")

file.writelines(["Line1\n","Line2\n","Line3"])
That was writing, good and all, but now you need to get from the file.
There are two ways to do this, readlines and read

read can either read a certain amount of characters or the full file as a single string.

file.read() This is the full file
file.read(5) The first 5 characters

Then there's readlines

print(file.readlines()) this would print a table of each line in the file.

["Line1","Line2","Line3"] Etc etc

Great!
Now you can read and write to files, in no time you'll be a python expert!

My next tutorial will either be databases or user interface.

Till next time!
 
  • Like
Reactions: Malcolm

William

Active Coder
Sep 7, 2019
178
32
38
So what does this mean? Like what would I use this for?
As far as I'm aware, it essentially means to handle the Input(I) and Output(O) of a File.

So, look at this:
Code:
file = open("FileName.txt","w")

file.writelines(["Line1\n","Line2\n","Line3"])
So, you open up the File. Then, the 'w' bit means that you're going to be inserting something into it(Input). So you're handling the behaviour of the Input.

This is my current knowledge anyway. I don't have that much knowledge of handling Files in Programming.