0% found this document useful (0 votes)
46 views3 pages

Python File Handling

The document provides an overview of Python file handling, including how to open, read, write, and append to files using various modes. It emphasizes the use of 'with open()' for automatic file closure and details methods like read(), readline(), and writelines() for reading, as well as write() for writing. Additionally, it covers cursor movement in files using seek() and tell() functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views3 pages

Python File Handling

The document provides an overview of Python file handling, including how to open, read, write, and append to files using various modes. It emphasizes the use of 'with open()' for automatic file closure and details methods like read(), readline(), and writelines() for reading, as well as write() for writing. Additionally, it covers cursor movement in files using seek() and tell() functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python File Handling

1. Opening a File (open() and with open())

file = open("[Link]", "r") # Open file in read mode

[Link]() # Always close the file after use

with open("[Link]", "r") as file:

pass # 'with' automatically closes the file after use

Modes:

• "r" → Read (default, file must exist)

• "w" → Write (creates or overwrites file)

• "a" → Append (adds to file, doesn’t overwrite)

• "r+" → Read & Write (file must exist)

• "w+" → Read & Write (creates or overwrites)

• "a+" → Read & Append (creates if missing)

• "rb", "wb", "ab" → Binary mode

2. Reading a File

file = open("[Link]", "r")

print([Link]()) # Reads the entire file

[Link]()

file = open("[Link]", "r")

print([Link]()) # Reads one line

[Link]()

file = open("[Link]", "r")


print([Link]()) # Reads all lines as a list

[Link]()

3. Writing to a File

file = open("[Link]", "w")

[Link]("Hello, Python!") # Overwrites the file

[Link]()

file = open("[Link]", "w")

[Link](["Line 1\n", "Line 2\n"]) # Writes multiple lines

[Link]()

4. Appending to a File

file = open("[Link]", "a")

[Link]("\nNew Line Added") # Adds without deleting previous content

[Link]()

5. Seek & Tell (Moving Cursor in File)

file = open("[Link]", "r")

print([Link]()) # Get current cursor position

[Link](5) # Move cursor to position 5

print([Link]()) # Read from new position

[Link]()

Summary
• Read: read(), readline(), readlines()
• Write: write(), writelines()

• Modes: "r", "w", "a", "r+", "w+", "a+"

• Seek & Tell: seek(position), tell()

• Use with for auto file closing (recommended but not required).

You might also like