python - 在python中将行号添加到字符串中

标签 python python-2.7

我有一个以下格式的文本文件:

"This is record #1"
"This is record #2"
"This is record #3"

我需要以下格式的输出:

Line number (1) --\t-- "This is Record # 1"
2-- \t-- "This is Record # 2"
3-- \t-- "This is Record # 3" 

当前代码:

f = open("C:\input.txt","r")
write_file = open("C:\output.txt","r+")
while True:
    line = f.readline()
    write_file.write(line)
    if not line : break
write_file.close()
f.close()

最佳答案

尝试以这种方式遍历您的文件:

f = open('workfile', 'r')
for num,line in enumerate(f):
    print(num+" "+line)

关于python - 在python中将行号添加到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975443/

相关文章:

python - 无法在 flask-sqlalchemy 中创建自引用外键

python - 如何从 XML 服务器操作调用 python 方法?

python GTK : Scrollable Grid with clickable images

python-2.7 - 提高 TesseractError(状态,错误)pyocr.error.TesseractError : (-1073741819, '')

macos - 在 Mac OS 下的 Python 2.7 中使用 Tkinter + Pillow (PIL) 时,PNG 图像不显示

python - 如何只接受3-8之间的整数而不接受字符串? (Python 2.7.5)

http - Python,Detect 是一个 URL 需要是 HTTPS 还是 HTTP

python - 在 Python 中有效地在二维 map 上进行扩散

python - 使用 lambda 从头开始​​删除列表条目

python - 在我的函数中循环遍历字典值