[英]How to append the line number to each line in a text (.txt) file?
我創建了兩個函數,一個用於計算文本文件中的行數 (count_lines),第二個 (write_numbers) 用於 append 從 0 開始到文本文件每一行的行號。 我的計數線 function 工作正常,但寫入數字 function 給我一個錯誤。 引發了 TypeError,但我在代碼中將數字轉換為字符串。 不知道這里發生了什么。 每個 function 的代碼和規格如下。
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)
問題是您試圖打開文件兩次:
file = open(filepath,'a')
n = count_lines(file)
然后,在count_lines
:
def count_lines(filepath):
...
file = open(filepath)
...
您正在嘗試打開一個文件,其path
參數是文件 object 而不是路徑!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.