如何将行号添加到输出文件? [英] How to add line numbers to an output file?
问题描述
def main():
(i)在范围内(10):
print(我爱蟒蛇)
print(Good bye!)
然后输出文件是:
1 def main():
2 for i in range 10):
3 print(我爱蟒蛇)
4 print(Good bye!)
我知道如何创建一个新的输出文件,但我很难在每行添加行号。请帮忙!我的程序是:
$ $ $ code $ filename $ input $($)请输入文件名以保存输出:)
openfile = open(filename,r)
readfile = openfile.readlines()
out_file = open(filename2,w)
save = out_file.write(FileWithLines)
枚举
( https://docs.python.org/2/library/functions.html#enumerate )。 enumerate
是一个内置函数,它将一个序列(string,list,dict,set,...)作为输入,并生成带有计数器的元组,并生成相应的值(开头文件名r)作为开放文件:开放(文件名2,w)。
)as out_file:
for j,enumerate(openfile)中的行:
out_file.write('{0:< 5} {1}'.format(j + 1,line))
Write a program that asks the user for a file containing a program and a name for an output file. Your program should then write the program, with line numbers to the output file. For example, if the input file is:
def main():
for i in range(10):
print("I love python")
print("Good bye!")
Then the output file would be:
1 def main():
2 for i in range(10):
3 print("I love python")
4 print("Good bye!")
I know how to create a new output file but I have difficulty in adding line numbers to each line. please help! My program is:
filename = input("Please enter a file name: ")
filename2 = input("Please enter a file name to save the output: ")
openfile = open(filename, "r")
readfile = openfile.readlines()
out_file = open(filename2, "w")
save = out_file.write(FileWithLines)
First, it is best to use the with ...
syntax when using files (https://docs.python.org/2/tutorial/inputoutput.html).
Then, all you have to do is use enumerate
(https://docs.python.org/2/library/functions.html#enumerate). enumerate
is a built-in function that takes a sequence (string, list, dict, set, ...) as input and generates tuples with a counter and the corresponding value of the sequence.
with open(filename, "r") as openfile:
with open(filename2, "w") as out_file:
for j, line in enumerate(openfile):
out_file.write('{0:<5}{1}'.format(j+1, line))
这篇关于如何将行号添加到输出文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!