编写一个程序,要求用户提供包含程序和输出文件名称的文件。

时间:2015-03-25 21:34:24

标签: python text formatting

编写一个程序,要求用户提供包含程序和输出文件名称的文件。然后,您的程序应该编写程序,并在输出文件中添加行号。例如,如果输入文件是:

def main():
    for i in range(10):
        print("I love python")
    print("Good bye!")

然后输出文件将是:

1   def main():
2       for i in range(10):
3           print("I love python")
4       print("Good bye!")

我知道如何创建新的输出文件,但我很难在每行添加行。请帮忙! 我的节目是:

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)

2 个答案:

答案 0 :(得分:1)

您可能希望使用enumerate遍历文件中的每一行:

for line_number, line in enumerate(readfile):
    new_line = ???        # make the new line by adding a line number
    readfile[line_number] = new_line

答案 1 :(得分:0)

enumerate迭代输入文件的每一行,并通过字符串格式化将内容写入新文件。

输入文件

input2.txt

def main():
    for i in range(10):
        print("I love python")
    print("Good bye!")

<强>码

filename = raw_input("Please enter a file name: ")
filename2 = raw_input("Please enter a file name to save the output: ")

openfile = open(filename, "r")
readfile = openfile.readlines()


out_file = open(filename2, "w")
for i , line in enumerate(readfile):
    out_file.write("%d %s" %(i+1, line))

out_file.close()

<强>输出:

vivek@vivek:~/Desktop/stackoverflow/anna$ python 7.py 
Please enter a file name: input2.txt
Please enter a file name to save the output: output2.txt

输出文件

output2.txt

1 def main():
2     for i in range(10):
3         print("I love python")
4     print("Good bye!")

语句。

filename = raw_input("Please enter a file name: ")
filename2 = raw_input("Please enter a file name to save the output: ")

with open(filename, "r") as fp:
    with open(filename2, "w") as fp2:
        for i , line in enumerate(fp.readlines()):
            fp2.write("%d %s" %(i+1, line))

注意:

在Python 2.x中使用raw_input()

在Python 3.x中使用input()