Learn to Code via Tutorials on Repl.it!

← Back to all posts
Python File Handling
VivaanSa (30)

File Handling in Python

The function for working with files in Python is the open() function.

open() Takes 2 parameters file, and mode.

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

You can also specify if the file should be Handled as binary or text(this is default)

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (could be images)

To close a file use f.close()
It is a good habit to close a file after opening

Code

For opening a simple txt file.

f = open("mytestfile.txt")

Open an image

f = open("myimage.png", "rb")

r For Opening to READ
b For Opening as BINARY

If the file is located in a folder, you will have to open from the file path, like this:

f = open("folder\blahblahblah.txt", "rt")
print(f.read())

Make sure the file exists, or else you will get an error!

Read files

Use f.read() to read a file, but first you have to open the file to read:

f = open("testfile.txt", "r")
readfile = f.read()
print(readfile)

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

Return the 20 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(20))

Return the 35 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(35))

Read Lines

You can return one line by using the readline() method:

f = open("attacts.txt", "r")
print(f.readline())

Print the first 2 lines of the file:

f = open("doopy.txt", "r")
print(f.readline())
print(f.readline())

Write to an Existing File:

To write to a file, use f.write(). Make sure you open the file as "w or a" first:

w - for rewriting the ENTIRE file.
a - for appending(adding) to the file

Add something to demofile.txt

f = open("demofile.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("demofile.txt", "r")
print(f.read())

Overwrite demofile.txt

f = open("demofile.txt", "w")
f.write("Oops! I have deleted the content!")
f.close()

#open and read the file after the writing:
f = open("demofile.txt", "r")
print(f.read())

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Example
Create a new file if it does not exist:

f = open("myfile.txt", "w")

Delete A File

To delete a file, you must import the OS module, and run its os.remove() function:

Example
Remove the file "demofile.txt":

import os
os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Example
Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Remove the folder "myfolder":

import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

Closing

That's it for today! Happy coding!!

Comments
hotnewtop
DakshSharma3 (0)

How can we delete specific content inside the file

bungulbungul (0)

@DakshSharma3 this is @VivaanSa (i was banned on other acc)

here ya go:

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

Return the 20 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(20))

Return the 35 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(35))

Read Lines

You can return one line by using the readline() method:

f = open("attacts.txt", "r")
print(f.readline())

Print the first 2 lines of the file:

f = open("doopy.txt", "r")
print(f.readline())
print(f.readline())
DakshSharma3 (0)

@bungulbungul How can I delete content inside the file though?