Python_File_IO_Commands
Python_File_IO_Commands
1. OPENING A FILE
Syntax:
file = open("filename.txt", "mode")
Modes:
'r' : Read (default)
'w' : Write (creates file or overwrites)
'a' : Append
'x' : Create (fails if file exists)
'b' : Binary mode
't' : Text mode (default)
'r+' : Read and Write
Example:
file = open("data.txt", "w")
2. WRITING TO A FILE
Syntax:
file.write("your text")
Example:
file = open("data.txt", "w")
file.write("Welcome to Python!")
file.close()
Methods:
file.read(size) Read 'size' characters
file.readline() Read one line
file.readlines() Read all lines (as list)
Example:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
4. APPENDING TO A FILE
Example:
Python File Input/Output (I/O) - All Commands
Syntax:
with open("filename", "mode") as file:
# do something
Example:
with open("data.txt", "r") as file:
content = file.read()
print(content)
Example:
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
file.read(size)
file.readline()
file.readlines()
file.write(text)
file.writelines(list_of_strings)
file.seek(offset)
file.tell()
file.close()
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File not found")
9. DELETE A FILE
import os
os.remove("data.txt")
Python File Input/Output (I/O) - All Commands
import os
os.mkdir("myfolder") # create folder
open("myfolder/new.txt", "w") # create file inside folder