Create a txt file write few lines in it.
Search any word and write how many times it has been used.
af=open("test2.txt",'a')
lines_of_text = ("One line of text here \n Second line \n third line")
af.writelines('\n' + lines_of_text)
af.close()
#Program to read data from data file in read mode and
#count the particular word occurrences in given string,
#number of times in python.
f=open("test2.txt",'r')
read=f.readlines()
f.close()
times=0 #the variable has been created to show the number of times the loop runs
times2=0 #the variable has been created to show the number of times the loop runs
chk=input("Enter String to search : ")
count=0
for sentence in read:
line=sentence.split()
times+=1
for each in line:
line2=each
times2+=1
if chk==line2:
count+=1
print("The search String ", chk, "is present : ", count, "times")
The search String line is present : 3 times
Write a python program to perform read and write operation onto a student.csv filehaving fields as roll number, name
import csv
# Function to write student data to a CSV file
def write_student_data(filename):
# Sample student data
students = [
{'roll_number': 101, 'name': 'Alice', 'stream': 'Science', 'percentage': 85.5},
{'roll_number': 102, 'name': 'Bob', 'stream': 'Commerce', 'percentage': 78.},
{'roll_number': 103, 'name': 'Charlie', 'stream': 'Arts', 'percentage': 90.2},
{'roll_number': 104, 'name': 'David', 'stream': 'Science', 'percentage': 88.4},
{'roll_number': 105, 'name': 'Eve', 'stream': 'Commerce', 'percentage': 92.1},
]
# Writing to the CSV file
with open(filename, mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['roll_number', 'name', 'stream', 'percentage'])
writer.writeheader() # Write the header
writer.writerows(students) # Write the student data
# Function to read student data from a CSV file
def read_student_data(filename):
try:
with open(filename, mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
print(f"Roll Number: {row['roll_number']}, Name: {row['name']}, Stream: {row['stream']}, Percentage:
except FileNotFoundError:
print("The file was not found.")
# Main program execution
if __name__ == "__main__":
csv_file = 'student.csv'
# Write student data to CSV
write_student_data(csv_file)
# Read and display student data from CSV
print("Student data from CSV file:")
read_student_data(csv_file)
Student data from CSV file:
Roll Number: 101, Name: Alice, Stream: Science, Percentage: 85.5
Roll Number: 102, Name: Bob, Stream: Commerce, Percentage: 78.0
Roll Number: 103, Name: Charlie, Stream: Arts, Percentage: 90.2
Roll Number: 104, Name: David, Stream: Science, Percentage: 88.4
Roll Number: 105, Name: Eve, Stream: Commerce, Percentage: 92.1
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js