OneCompiler

File Handling in Python - Python class

168

File Handling in Python

Opening a File

file_name = "file.txt"
f0 = open(file_name, "w")
print(f0.name)  # Get current open filename
print(type(f0))  # Output: _io.TextIOWrapper

Writing to a File

file_name = "file.txt"
f0 = open(file_name, 'w')

str1 = "current date is 07/03"
f0.write(str1)  # To add a single string to a file
f0.write("\n")  # To add a new line

list1 = ["str1", "Str2", "str3"]
f0.writelines(list1)  # To write multiple lines from a list

f0.close()

Reading from a File

f0 = open("file.txt")
print(f0.read())  # Read entire file content
print(type(f0.read()))  # Check the type of read output

print("##########")
print(f0.readline())  # Read single line from cursor position
print("##########")
print(f0.readlines())  # Read all lines in file as a list

f0.close()

Read Methods:

  • read(): Gets the entire file content as a string.
  • readline(): Gets a single line from the cursor position.
  • readlines(): Gets all lines in a file as a list.

File Cursor Management

# seek() moves the cursor position
# tell() shows the cursor position

f0 = open("file.txt", "r")
print(f0.tell())  # Get current cursor position

f0.readline()
f0.seek(0)  # Move cursor to the first line

print(f0.tell())  # Get updated cursor position

f0.close()

Cursor Position Methods:

  • seek(0): Move cursor to the beginning of the file.
  • seek(1): Move cursor to the end of the file (incorrect, should use seek() with file length).
  • tell(): Show the current cursor position.

Using with Statement (Context Manager)

# Using context manager to handle files
with open("file1.txt", 'r') as f0:
    data = f0.read()
    print(data)

Benefits of with Statement:

  • Automatically manages resources.
  • No need to explicitly close the file.

Equivalent manual approach:

f0 = open("file1.txt", "r")
data = f0.read()
print(data)
f0.close()