Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将带编号的行从一个.txt打印到另一个.txt_Python_Python 3.x_File - Fatal编程技术网

Python 如何将带编号的行从一个.txt打印到另一个.txt

Python 如何将带编号的行从一个.txt打印到另一个.txt,python,python-3.x,file,Python,Python 3.x,File,我试图将一行文本从一个.txt文件打印到另一个.txt文件,但每行都在第二个文件中编号 例如,如果第一个1.txt文件为: Chocolate Vanilla Strawberry 第二个2.txt文件应为: [0] Chocolate [1] Vanilla [2] Strawberry 我正在尝试使用Python3代码来做这件事,请帮助。谢谢这应该可以做到: file1 = open('1.txt', 'r') file2 = open('2.txt', 'w') for idx

我试图将一行文本从一个.txt文件打印到另一个.txt文件,但每行都在第二个文件中编号

例如,如果第一个1.txt文件为:

Chocolate
Vanilla
Strawberry

第二个2.txt文件应为:

[0] Chocolate
[1] Vanilla
[2] Strawberry


我正在尝试使用Python3代码来做这件事,请帮助。谢谢

这应该可以做到:

file1 = open('1.txt', 'r') 
file2 = open('2.txt', 'w')

for idx,line in enumerate(file1):
    file2.write('['+str(idx)+'] '+line)

file1.close()
file2.close()

您尝试了什么?fh_in=open(输入('Enter input file name:'),'r')fh_out=open(输入('Enter output file name:'),'w'),用于i,fh_in.items()中的行:fh_out.write('{}={}'。格式(i+1,line.strip())fh_in.close()fh_out.close()在注释中阅读代码很困难,因为它没有保留格式。请将您的代码输入问题。谢谢,它正在工作,但似乎只打印第一行嗨,罗布!我刚刚在Python3.5下测试了我的脚本,并且能够毫无问题地创建文件2.txt。您的输入文件1.txt是否有问题?