Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. File Handling
  5. Reading and Writing Files in Python

Reading and Writing Files in Python

Python provides methods to read from and write to files.

Reading Files:

  • read(): Reads the entire file content as a string.
  • readline(): Reads one line at a time.
  • readlines(): Reads all lines and returns them as a list.

Example:

# Open a file in read mode
file = open("example.txt", "r")

# Read the entire file
content = file.read()
print(content)

# Read one line at a time
line = file.readline()
print(line)

# Read all lines as a list
lines = file.readlines()
print(lines)

# Close the file
file.close()

Writing Files:

  • write(): Writes a string to the file.
  • writelines(): Writes a list of strings to the file.

Example:

# Open a file in write mode
file = open("example.txt", "w")

# Write a string to the file
file.write("Hello, World!\n")

# Write a list of strings to the file
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)

# Close the file
file.close()

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *