I created two functions, one to count the lines (count_lines) in a text file and a second (write_numbers) to append the line number starting at 0 to each line of the text file. My count lines function works properly but the write numbers function gives me an error. TypeError is raised but I am converting the number to a string in my code. Not sure what is going on here. Code and specifications for each function below.
Error:
>>> funcs.write_numbers('files/writefile1.txt',5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/codio/workspace/exercise1/funcs.py", line 45, in write_numbers
n = count_lines(file)
File "/home/codio/workspace/exercise1/funcs.py", line 19, in count_lines
file = open(filepath)
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
Text File:
This file is used to test count_lines
It has 6 lines
3
4
5
6
def count_lines(filepath):
"""
Returns the number of lines in the given file.
Lines are separated by the '\n' character, which is standard for Unix files.
Parameter filepath: The file to be read
Precondition: filepath is a string with the FULL PATH to a text file
"""
# HINT: Remember, you can use a file in a for-loop
file = open(filepath)
line_count = 0
for line in file:
if line != '/n':
line_count += 1
return line_count
def write_numbers(filepath,n):
"""
Writes the numbers 0..n-1 to a file.
Each number is on a line by itself. So the first line of the file is 0,
the second line is 1, and so on. Lines are separated by the '\n' character,
which is standard for Unix files. The last line (the one with the number
n-1) should NOT end in '\n'
Parameter filepath: The file to be written
Precondition: filepath is a string with the FULL PATH to a text file
Parameter n: The number of lines to write
Precondition: n is an int > 0.
"""
# HINT: You can only write strings to a file, so convert the numbers first
file = open(filepath,'a')
n = count_lines(file)
i = 0
for line in file:
if line != '/n':
i += 1
file.write(str(i))
if i == n-1:
break
print(file)
The problem is that you are trying to open the file twice:
file = open(filepath,'a')
n = count_lines(file)
Then, in count_lines
:
def count_lines(filepath):
...
file = open(filepath)
...
You are trying to open a file with its path
argument being a file object rather than a path !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.