Write a program to perform the below operations on files:
- Create a text file and write a string to it.
- Read an entire text file.
- Read a text file line by line.
- Write a string to a file.
- Write a list of strings to a file.
- Count the number of lines, words in a file.
Code
# perform file operation# create text file and write a string to itf = open("test.txt", "w")f.write("This is a test file")# read the filef = open("test.txt", "r")print(f.read())# read the file line by linef = open("test.txt", "r")print(f.readline())# write a string to the filef = open("test.txt", "a")f.write("This is a test file")# write a list of strings to the filef = open("test.txt", "a")f.writelines(["This is a test file", "This is a test file"])# count the number of lines in the filef = open("test.txt", "r")print(len(f.readlines()))# count the number of words in the filef = open("test.txt", "r")print(len(f.read().split()))f.close()
Output
This is a test file
This is a test file
1
17
open test.txt file and count the words and yes explore more
0 Comments
Post a Comment