SimpleTuts.com

Python File Handling

File handling in Python refers to operations performed on files, such as reading from or writing to them. You can open files using the `open()` function, specify modes like 'r' for reading or 'w' for writing, manipulate file content using methods like `read()`, `write()`, and `close()` to manage resources properly.

Modes in Python file handling dictate how a file is opened and manipulated



Read file




f = open("demofile.txt", "r")
print(f.read())
f.close()
                
Python Online Compiler

Read Only Parts of the File




# Read file
f = open("demofile.txt", "r")
print(f.read(6))
print(f.readline())
print(f.readline())
f.close()
                
Python Online Compiler

Append content to the file




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

#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
f.close()
                
Python Online Compiler

Overwrite the content




#Write file
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:
f = open("demofile3.txt", "r")
print(f.read())
f.close()
                
Python Online Compiler

Create an empty file




#Create file
f = open("myfile.txt", "x")
                
Python Online Compiler

Delete a file




import os

#Delete file
import os
if os.path.exists("myfile.txt"):
  os.remove("myfile.txt")
else:
  print("The file does not exist")
                
Python Online Compiler