Python Tutorial
Open, Read, Delete a File in Python With Example
Open a File on the Server
Assume we have the following file in the Python folder:
ws_file.txt
Hello! Welcome to wscube tech
This file is for testing purposes.
You can use the built-in open() function to open the file. This function will return a file object, which will contain a read() method for the purpose of reading the content in the file.
Example:
p = open("ws_file.txt", "r")
print(p.read())
Output:
Hello! Welcome to wscube tech
This file is for testing purposes
Example:
p = open("D:\\myfiles\\ws_file.txt", "r")
print(p.read())
Output:
Hello! Welcome to wscube tech
This file is for testing purposes
Read Only Parts of File
By default, the read() function returns the complete text, but you can also specify the number of characters to return.
Example:
Show the first 5 characters of the file:
f = open("wscfile.txt", "r")
print(f.read(5))
Output:
C:\Users\My Name>python demo_file_open2.py
Hell
Hell
Read Lines Using readline() Method
The readline()
method can be used to return a single line:
Example:
Read one line of the file:
f = open("wscfile.txt", "r")
print(f.readline())
Output:
C:\Users\My Name>python demo_file_readline.py
Hello! Welcome to wscfile.txt
The readline() method can be used to return a single line.
Example:
Read two lines of the file:
f = open("wscfile.txt", "r")
print(f.readline())
print(f.readline())
Output:
C:\Users\My Name>python demo_file_readline2.py
Hello! Welcome to wscfile.txt
This file is for testing purposes.
By looping, you can read the whole file, line by line.
Example:
Loop through the file line by line:
f = open("wscfile.txt", "r")
for x in f:
print(x)
Output:
C:\Users\My Name>python demo_file_readline3.py
Hello! Welcome to wscfile.txt
This file is for testing purposes.
Good Luck!
Delete a File in Python
You must import the OS module and use its os.remove()
method to delete a file:
import os
os.remove("demo_file.txt")