Python Forum
File Handling not working properly
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File Handling not working properly
#1
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.
Error:
Traceback (most recent call last): File "/home/coder/project/file_ops.py", line 123, in <module> main() File "/home/coder/project/file_ops.py", line 118, in main write_first_line_to_file(open("sampletext.txt", "r"), "online.txt") File "/home/coder/project/file_ops.py", line 64, in write_first_line_to_file raise NotImplementedError() NotImplementedError
Error:
Function write_first_line_to_file Multiline test returned this error: 'str' object has no attribute 'readline'. Single line test returned this error: 'str' object has no attribute 'readline'. Empty string test returned this error: 'str' object has no attribute 'readline'. Newline-prefixed test returned this error: 'str' object has no attribute 'readline'. Function read_even_numbered_lines Short file test did not pass. Expected (newlines added for legibility): ['He kindly stopped for me;\n', 'And Immortality.'] Got (newlines added for legibility): ['He kindly stopped for me;', 'And Immortality.'] Long file test did not pass. Expected (newlines added for legibility): ['Admit impediments. Love is not love\n', 'Or bends with the remover to remove:\n', 'That looks on tempests and is never shaken;\n', "Whose worth's unknown, although his heighth be taken.\n", "Within his bending sickle's compass come;\n", 'But bears it out even to the edge of doom:\n', 'I never writ, nor no man ever loved.'] Got (newlines added for legibility): ['Admit impediments. Love is not love', 'Or bends with the remover to remove:', 'That looks on tempests and is never shaken;', "Whose worth's unknown, although his heighth be taken.", "Within his bending sickle's compass come;", 'But bears it out even to the edge of doom:', 'I never writ, nor no man ever loved.']
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()
Reply


Messages In This Thread
File Handling not working properly - by TheLummen - Feb-15-2024, 04:08 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple code not working properly tmv 2 476 Feb-28-2025, 09:27 PM
Last Post: deanhystad
  Excel isnt working properly after python function is started IchNar 2 1,219 May-01-2024, 06:43 PM
Last Post: IchNar
  file handling Newbee question middlecope 2 1,578 Jan-18-2023, 03:09 PM
Last Post: middlecope
Star python exception handling handling .... with traceback mg24 3 3,390 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  File handling issue GiggsB 4 2,479 Mar-31-2022, 09:35 PM
Last Post: GiggsB
  How can I solve this file handling issue? GiggsB 17 6,122 Feb-14-2022, 04:37 AM
Last Post: GiggsB
Question apk file not working on android polya001 0 1,634 Feb-06-2022, 11:58 PM
Last Post: polya001
  How to solve this file handling issue? GiggsB 3 2,461 Jan-10-2022, 09:36 AM
Last Post: Gribouillis
  Subprocess.Popen() not working when reading file path from csv file herwin 13 23,683 May-07-2021, 03:26 PM
Last Post: herwin
  fpdf orientation not working properly KatMac 1 4,603 May-02-2021, 10:47 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020