Contents: Click for quick access
1. Creating New File in Python:2. Opening Files in Python:i. Opening file from same folder:ii. Opening file from different folder:3.Reading Files in Python:i. Read one line of the file:ii. Read two lines of the file:iii. Read the file line by line :4. Writing to Files in Python:i. Append content to the file:ii. Overwrite content to the file:5. Closing Files in Python:6. Deleting Files in Python:
1. Creating New File in Python:
Syntax:
file = open("python.txt", "x")
2. Opening Files in Python:
i. Opening file from same folder:
Syntax:
file = open("python.txt", "r")
print(file.read())
ii. Opening file from different folder:
Syntax:
file = open("D:\\myfiles\python.txt", "r")
print(file.read())
3.Reading Files in Python:
i. Read one line of the file:
Syntax:
file = open("python.txt", "r")
print(file.readline())
ii. Read two lines of the file:
Syntax:
file = open("python.txt", "r")
print(file.readline())
print(file.readline())
iii. Read the file line by line :
Syntax:
file = open("python.txt", "r")
for a in file:
print(a)
4. Writing to Files in Python:
i. Append content to the file:
Syntax:
file = open("python.txt", "a")
file.write("Now the file has more content!")
file.close()
ii. Overwrite content to the file:
Syntax:
file = open("python.txt", "w")
file.write("Previous content deleted!")
file.close()
5. Closing Files in Python:
Syntax:
file = open("python.txt", "r")
print(file.readline())
file.close()
6. Deleting Files in Python:
Syntax:
import os
if os.path.exists("python.txt"):
os.remove("python.txt")
else:
print("The file does not exist")