![]() |
File Handling not working properly - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: File Handling not working properly (/thread-41602.html) |
File Handling not working properly - TheLummen - Feb-15-2024 I've trying to find what is the error in the following code but I still get the error. Does anyone have any idea how to resolve this as I have been trying(debugging) but nothing works. Thank you.
def read_file(file_name): """ Reads in a file. [IMPLEMENT ME] 1. Open and read the given file into a variable using the File read() function 2. Print the contents of the file 3. Return the contents of the file Args: file_name: the name of the file to be read Returns: string: contents of the given file. """ with open(file_name, "r") as file: contents = file.read() print(contents) return contents raise NotImplementedError() def read_file_into_list(file_name): """ Reads in a file and stores each line as an element in a list [IMPLEMENT ME] 1. Open the given file 2. Read the file line by line and append each line to a list 3. Return the list Args: file_name: the name of the file to be read Returns: list: a list where each element is a line in the file. """ lines = [] with open(file_name, "r") as file: lines = file.readlines() return lines raise NotImplementedError() def write_first_line_to_file(file_contents, output_filename): """ Writes the first line of a string to a file. [IMPLEMENT ME] 1. Get the first line of file_contents 2. Use the File write() function to write the first line into a file with the name from output_filename We determine the first line to be everything in a string before the first newline ('\n') character. Args: file_contents: string to be split and written into output file output_filename: the name of the file to be written to """ with open(output_filename, "w") as file: file.write(file_contents.readline()) raise NotImplementedError() def read_even_numbered_lines(file_name): """ Reads in the even numbered lines of a file [IMPLEMENT ME] 1. Open and read the given file into a variable 2. Read the file line-by-line and add the even-numbered lines to a list 3. Return the list Args: file_name: the name of the file to be read Returns: list: a list of the even-numbered lines of the file """ even_lines = [] with open(file_name, "r") as file: lines = file.readlines() even_lines = [line.strip() for i, line in enumerate(lines) if i % 2 != 0] return even_lines raise NotImplementedError() def read_file_in_reverse(file_name): """ Reads a file and returns a list of the lines in reverse order [IMPLEMENT ME] 1. Open and read the given file into a variable 2. Read the file line-by-line and store the lines in a list in reverse order 3. Print the list 4. Return the list Args: file_name: the name of the file to be read Returns: list: list of the lines of the file in reverse order. """ with open(file_name, "r") as file: lines = file.readlines() return list(reversed(lines)) raise NotImplementedError() ''' Here are some sample commands to help you run/test your implementations. Feel free to uncomment/modify/add to them as you wish. ''' def main(): file_contents = read_file("sampletext.txt") print(read_file_into_list("sampletext.txt")) write_first_line_to_file(open("sampletext.txt", "r"), "online.txt") print(read_even_numbered_lines("sampletext.txt")) print(read_file_in_reverse("sampletext.txt")) if __name__ == "__main__": main() RE: File Handling not working properly - deanhystad - Feb-15-2024 Quote: I have been trying but nothing works.What have you been trying? Next time include that information in your post. Also include the error message you are getting, the entire message and the trace. I ran your code and I don't get any errors. The error message in your post indicates you passed a string instead of a file (text IO wrapper) as an argument when calling write_first_line_to_file(), but that does not happen in the code in your post. RE: File Handling not working properly - Pedroski55 - Feb-15-2024 Agree with deanhystad, no problem: path2file = '/home/pedro/Desktop/fret.txt' def read_file(file_name): with open(file_name, "r") as file: contents = file.read() print(contents) read_file(path2file)Ouputs the text of path2file. RE: File Handling not working properly - TheLummen - Feb-15-2024 Thank you for your reply. Changes have been made. The code has been debugged and should work properly but when I run the automated tastes of a platform I get the errors mentioned and can't pass the assignment, which makes no sense as all looks good. RE: File Handling not working properly - deanhystad - Feb-15-2024 Don't edit your original post, post new information in a new post. Now I don't know what error messages are associated with what code. My guess is that even though the coding may be correct, your understanding of the assignment is not. You wrote a working python program that solves the wrong problem. Can you post a description of the assignment? RE: File Handling not working properly - TheLummen - Feb-15-2024 What do you mean !? There is the original post including all the relevant information. The first error is the one I get from the terminal and the second from the assessment corrections/tests. The description of the assessment is included in the code comments. RE: File Handling not working properly - deanhystad - Feb-16-2024 I read the comments in your code this time. Guess what, you didn't follow your own instructions! Quote:def write_first_line_to_file(file_contents, output_filename):Under Args, file contents is a STRING to be split and written into output file. You are passing a file (actually a Text IO wrapper). Follow the instructions and you might pass those tests. You couldn't see the problem because you already rewrote the problem description in your head. That is a common problem. Are the tests each calling all your functions with different input files? RE: File Handling not working properly - Pedroski55 - Feb-16-2024 Try each of these 1 by 1 in your IDE, just change the paths to your paths. Not sure what raise NotImplementedError() is supposed to do, Python has many built-in Exception messages, like:Quote:NotADirectoryErrorenough for normal use! Try these 1 by 1 in your IDE: path2file = '/home/pedro/Desktop/fret.txt' savepath = '/home/pedro/tmp/X.txt' def read_file(file_name): print(f'reading the file {file_name}') with open(file_name, "r") as infile: contents = infile.read() print(f'The contents of the file are: {contents}') return contents X = read_file(path2file) def read_file_into_list(file_name): print(f'Reading {file_name} into a list ... ') with open(file_name, "r") as infile: lines = infile.readlines() return lines X = read_file_into_list(path2file) def write_first_line_to_file(file_name, savepath): # get the first element of the list: read_file_into_list(file_name) line = read_file_into_list(file_name)[0] with open(savepath, "w") as outfile: outfile.write(line) print(f'Saved first line of input file as {savepath}') return line X = write_first_line_to_file(path2file, savepath) def read_even_numbered_lines(file_name, output_filename): with open(file_name, "r") as infile, open(savepath, 'w') as outfile: lines = infile.readlines() even_lines = [lines[i] for i in range(0, len(lines), 2)] output = ''.join(even_lines) outfile.write(output) print(f'Even numbered lines saved to {savepath}') return even_lines X = read_even_numbered_lines(path2file, "X.txt") def read_file_in_reverse(file_name, output_filename): with open(file_name, "r") as infile, open(savepath, 'w') as outfile: lines = infile.readlines() for i in range(len(lines)-1, -1, -1): outfile.write(lines[i]) revlist = [lines[i] for i in range(len(lines)-1, -1, -1)] print(f'Text lines reversed and saved to {savepath}') return revlist X = read_file_in_reverse(path2file, savepath)Maybe this will help! RE: File Handling not working properly - TheLummen - Feb-17-2024 Thank you for your time guys. Fix: Corrected file reading/writing methods by using proper Python file handling techniques (e.g., with open(...) as file) and adjusted logic to properly select even-numbered lines. def read_file(file_name): """ Reads in a file. [IMPLEMENT ME] 1. Open and read the given file into a variable using the File read() function 2. Print the contents of the file 3. Return the contents of the file Args: file_name: the name of the file to be read Returns: string: contents of the given file. """ ### WRITE SOLUTION HERE f = open(file_name, "r") whole_content = f.read() f.close() return whole_content raise NotImplementedError() def read_file_into_list(file_name): """ Reads in a file and stores each line as an element in a list [IMPLEMENT ME] 1. Open the given file 2. Read the file line by line and append each line to a list 3. Return the list Args: file_name: the name of the file to be read Returns: list: a list where each element is a line in the file. """ ### WRITE SOLUTION HERE f = open(file_name, "r") whole_content = f.readlines() f.close() return whole_content raise NotImplementedError() def write_first_line_to_file(file_contents, output_filename): """ Writes the first line of a string to a file. [IMPLEMENT ME] 1. Get the first line of file_contents 2. Use the File write() function to write the first line into a file with the name from output_filename We determine the first line to be everything in a string before the first newline ('\n') character. Args: file_contents: string to be split and written into output file output_filename: the name of the file to be written to """ ### WRITE SOLUTION HERE with open(output_filename, 'w') as file: updated_file = file.writelines(file_contents.split('\n')[0]) return None raise NotImplementedError() def read_even_numbered_lines(file_name): """ Reads in the even numbered lines of a file [IMPLEMENT ME] 1. Open and read the given file into a variable 2. Read the file line-by-line and add the even-numbered lines to a list 3. Return the list Args: file_name: the name of the file to be read Returns: list: a list of the even-numbered lines of the file """ ### WRITE SOLUTION HERE with open(file_name, 'r') as file: list_of_lines = file.readlines() even_line_list = [] for count, line in enumerate(list_of_lines): if count%2 == 1: even_line_list.append(line) return even_line_list raise NotImplementedError() def read_file_in_reverse(file_name): """ Reads a file and returns a list of the lines in reverse order [IMPLEMENT ME] 1. Open and read the given file into a variable 2. Read the file line-by-line and store the lines in a list in reverse order 3. Print the list 4. Return the list Args: file_name: the name of the file to be read Returns: list: list of the lines of the file in reverse order. """ ### WRITE SOLUTION HERE with open(file_name, 'r') as original: original_list = original.readlines() new_list = list(reversed(original_list)) return new_list raise NotImplementedError() ''' Here are some sample commands to help you run/test your implementations. Feel free to uncomment/modify/add to them as you wish. ''' def main(): file_contents = read_file("sampletext.txt") print(file_contents) print(read_file_into_list("sampletext.txt")) #write_first_line_to_file(file_contents, "online.txt") print(read_even_numbered_lines("sampletext.txt")) #print(read_file_in_reverse("sampletext.txt")) if __name__ == "__main__": main() |