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
#2
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.
Reply
#3
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.
Reply
#4
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.
Reply
#5
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?
Reply
#6
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.
Reply
#7
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):
""" 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
"""
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?
Reply
#8
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:NotADirectoryError
IndexError
NameError
enough 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!
Reply
#9
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  file handling Newbee question middlecope 2 784 Jan-18-2023, 03:09 PM
Last Post: middlecope
Star python exception handling handling .... with traceback mg24 3 1,284 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  File handling issue GiggsB 4 1,448 Mar-31-2022, 09:35 PM
Last Post: GiggsB
  How can I solve this file handling issue? GiggsB 17 3,593 Feb-14-2022, 04:37 AM
Last Post: GiggsB
Question apk file not working on android polya001 0 1,161 Feb-06-2022, 11:58 PM
Last Post: polya001
  How to solve this file handling issue? GiggsB 3 1,703 Jan-10-2022, 09:36 AM
Last Post: Gribouillis
  Subprocess.Popen() not working when reading file path from csv file herwin 13 15,123 May-07-2021, 03:26 PM
Last Post: herwin
  fpdf orientation not working properly KatMac 1 3,349 May-02-2021, 10:47 AM
Last Post: Pedroski55
Lightbulb Jupyter is not working properly brunolelli 3 2,996 Apr-23-2021, 03:22 AM
Last Post: Larz60+
  File handling knollfinder 3 2,058 Jun-28-2020, 07:39 PM
Last Post: knollfinder

Forum Jump:

User Panel Messages

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