0% found this document useful (0 votes)
8 views2 pages

Handling Files in Python

The document provides a comprehensive guide on handling files in Python, including writing, reading, appending, and counting lines and words in files. It also covers copying file contents, writing lists to files, and working with CSV files. Additionally, it includes a method for searching for a specific word within a file.

Uploaded by

ponjit.borgohain
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)
8 views2 pages

Handling Files in Python

The document provides a comprehensive guide on handling files in Python, including writing, reading, appending, and counting lines and words in files. It also covers copying file contents, writing lists to files, and working with CSV files. Additionally, it includes a method for searching for a specific word within a file.

Uploaded by

ponjit.borgohain
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

Handling Files in Python

1. Write to a file

with open("[Link]", "w") as f:


[Link]("Hello World")

2. Read entire file

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


data = [Link]()
print(data)

3. Read file line by line

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


for line in f:
print([Link]())

#strip() in Python is a string method used to remove unwanted characters (usually


whitespace) from the beginning and end of a string.

4. Append data to file

with open("[Link]", "a") as f:


[Link]("\nNew line added")

5. Count number of lines

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


count = len([Link]())
print("Total lines:", count)

6. Count words in a file

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


data = [Link]()
words = [Link]()
print("Total words:", len(words))
7. Copy contents from one file to another

with open("[Link]", "r") as f1, open("[Link]", "w") as f2:

[Link]([Link]())

8. Write list of strings to file

lines = ["Python\n", "Java\n", "C++\n"]

with open("[Link]", "w") as f:


[Link](lines)

9. Write data to CSV file

import csv

with open("[Link]", "w", newline="") as f:


writer = [Link](f)
[Link](["Name", "Marks"])
[Link](["Amit", 85])
[Link](["Riya", 90])

10. Read data from CSV file

import csv

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


reader = [Link](f)
for row in reader:
print(row)

11. Search a word in file

word = input("Enter word to search: ")

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


data = [Link]()
if word in data:
print("Word found")
else:
print("Word not found")

You might also like