如何将行号附加到文本(.txt)文件中的每一行

  • 本文关键字:文件 一行 txt 文本 python
  • 更新时间 :
  • 英文 :


我创建了两个函数,一个用于计算文本文件中的行数(count_lines(,另一个用于将从0开始的行号附加到文本文件的每一行。我的计数行函数工作正常,但写数字函数给了我一个错误。引发了TypeError,但我正在将代码中的数字转换为字符串。不确定这里发生了什么。以下每个功能的代码和规范。

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参数是文件对象而不是路径!

最新更新