In: Computer Science
In python Complete the function get_Astring(filename) to read the file contents from filename (note that the test will use the file data.txt and data2.txt provided in the second and third tabs), strip off the newline character at the end of each line and return the contents as a single string.
Program code to copy:-
#This function to reads the contents from file passed as
parameter and
#strip off the newline character at the end of each line and
#returns the contents as a single string.
def get_Astring(filename):
#Opening the file for reading
fin = open(filename, "r")
#Declaring a variable to hold the final
string after strip off new linw
string = ""
#for loop read the content of file line by
line and
#store each line into variable 'line' till end
of input file
for line in fin:
loc = 0;
#while loop will check
every character of line read from file and
#add the character to
'string' variable which is not a newline
while loc <
len(line):
if(line[loc] != '\n'):
string = string + line[loc]
loc = loc + 1
#closing file
fin.close()
#returns string without newline character
return string
#Code to test get_Astring() function by calling it in main()
function
def main():
#Prompt and reads filename from user
filename = input('Enter the file name: ')
#Calling function to get string without
newlinw character
string = get_Astring(filename)
#Displaying the value of string returned from
function
print(string)
#Calling main() function
main()
Screenshot of program code to understand the indentation:-
Screenshot of output:-
Origional content of file(data2.txt) used to test the program:-
Python is a general purpose, interpreted,
platform independent, dynamically typed,
object-oriented programming language.
It has a large collection of in-built library functions.