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")