File handling (Python)
File handling (Python)
Code :
def read_text(Myself):
with open(Myself,'r') as f:
return f.read()
print(read_text("/content/sample_data/Myself"))
Output :
Code:
Q3. Write a Python program to append text to a file and display the
text.
Code:
Code:
def file_to_list(Myself):
with open(Myself, 'r') as file:
return [line.strip() for line in file]
print(file_to_list("/content/sample_data/Myself"))
Output :
Q6. Write a Python program to read a file line by line store it into a variable.
Code:
def file_to_variable(Myself):
with open(Myself, 'r') as file:
return file.read()
print(file_to_variable("/content/sample_data/Myself"))
Output:
Q7. Write a Python program to read a file line by line store it into an array.
Code:
def file_to_array(Myself):
return file_to_list(Myself)
print(file_to_array("/content/sample_data/Myself"))
Output:
Q8. Write a python program to find the longest words.
Code:
def find_longest_word(Myself):
return max(open(Myself).read().split(), key=len)
print(find_longest_word("/content/sample_data/Myself"))
Output:
Q9. Write a Python program to count the number of lines in a text file
Code:
def count_lines(Myself):
with open(Myself, 'r') as file:
return sum(1 for line in file)
print(count_lines("/content/sample_data/Myself"))
Output:
Code: