file handling in python
Q 1. what is difference between read() and readlines() function, reads from a file in read mode and returns a list of all lines in the file.
ans. the read() reads from a file in read mode, and stores its contents in aa string type variable.
the readlines() functions, reads from a file in read mode and returns a list of all lines in the file.
Q 2. write a single loop to display all the contents of a text file poem.txt after removing leading and trailing white spaces.
ans. for line in file(“poem.txt”):
Q 3. which format of files can be created programmatically through python to store some data.
ans.(1) text files
Q 4. the read line method returns.
ans. a list of lines.
Q 5. which of the following mode refers to binary data.
(1)r (2)w (3)+ (4)b
ans. (d) b
Q 6 what is significance of file-object.
ans. through a file-object only, a python program can work with files stored on hardware. file objects are used to read and write data to a file on disk.
Q 7. what is difference between readline() and readlines() function.
ans. The readline() function reads from a file in read mode and returns the next line in the file or a blank string if there are no more lines. The data returned by readline() is string type.
the readlines() function, also read from a file in read mode and returns a list of all lines in the file .the data returned by readlines() is list list types.
Q 8. write a program to display all the records in a file along with line/record number.
if rec == ” “:
Q 9. read the code given below and answer the question.
if the file contain “GOOD” before execution, what will be contents of the file after execution of this code.
ans. The file would now contain “bye” only, because when an existing file opened in write mode(“w”), it truncates the existing data the file.
Q 10. write the code to print just the last line of a text file “data.txt”.
Q 11. write a function in python to count the number of lines in a text file “story.txt” which is starting with an alphabet ‘a’ or ‘A’.
for w in lines:
if w==”a” or w==”A”:
print(“total lines started with ‘a’ or ‘A’ “,count)
Q 12. write a method/function displaywords() in python to read lines from a text file story.txt, and display those words, which is less than 4 characters.
ans. def displaywords():
for w in word:
Q 13. a text file contains alphanumeric text(an.txt).
write a program that reads this text files and prints only the numbers or digits from the file.
for line in f:
for i in words:
for letter in i:
Q 14. write a function remove_lowercase() that accepts two filenames,and copies all lines that do not start with a lowercase letter from the frost file into the second.
ans. def remove_lowercase(infile,outfile):
for line in file(infile):
if not line in “abcdefghijklmnopqrstuvwxyz”
Q 15. write a function which receives a file name as parameter and reads and stores the file content in a list.
ans. def file_read(fname):