python:读入一个文件,每行重复两次 给输出行编号
示例: 给定此文件:
Invictus
Out of the night that covers me
Black as the pit from pole to pole
I thank whatever gods there may be
For my unconquerable soul
以下是输出:
1 Invictus
1 Invictus
2
2
3 Out of the night that covers me
3 Out of the night that covers me
4 Black as the pit from pole to pole
4 Black as the pit from pole to pole
5 I thank whatever gods there may be
5 I thank whatever gods there may be
6 For my unconquerable soul
6 For my unconquerable soul
这是我到目前为止的代码,我还没有弄清楚在每一行上放置双重编号所需的循环:
fileicareabout = open("ourownfile","r")
text = fileicareabout.readlines()
count = len(open("ourownfile").readlines( ))
fileicareabout.close()
def linecount(ourownfile):
count = 0
for x in open("ourownfile"):
count += 1
return count
for words in text:
print (str(linecount) + words) * 2
print
你是说每行粘贴两次时,编号需要增加吗?所以需要: 1不可侵犯
2不可侵犯
三
4个
5个晚上都在掩护我
如果是这样,循环应该如下所示:
乘法运算符(
*
)可能很方便。你知道吗示例:
遵循相同的逻辑:
输入文件:
输出.txt:
您可以使用enumerate对行号进行计数:
或者使用更新的print函数(python 3需要):
要获得准确的输出,您似乎跳过了第一行:
相关问题 更多 >
编程相关推荐