如何将文件的每行保存到新文件(每行新文件)并为多个原始文件执行此操作
我有5个文件,我想从中获取每行(总共24行)并将其保存到新文件中。我设法找到了一个可以做到这一点的代码,但是它们是这样,每当我必须手动更改适当的原始文件的数量和要将其保存到的文件的数量以及每行时的数量。
代码:
x1= np.loadtxt("x_p2_40.txt")
x2= np.loadtxt("x_p4_40.txt")
x3= np.loadtxt("x_p6_40.txt")
x4= np.loadtxt("x_p8_40.txt")
x5= np.loadtxt("x_p1_40.txt")
with open("x_p1_40.txt", "r") as file:
content = file.read()
first_line = content.split('\n', 1)[0]
with open("1_p_40_x.txt", "a" ) as f :
f.write("\n")
with open("1_p_40_x.txt", "a" ) as fa :
fa.write(first_line)
print(first_line)
我是Python的初学者,我不确定如何为此循环,因为我认为我需要一个循环?
谢谢你!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您在这里有多个文件,因此您可以在列表中定义其名称,并使用列表理解为所有文件打开所有内容:
由于这些文件句柄中的每一个都是一个迭代器,每次迭代它都会产生一条线路,您可以简单地
zip()
所有这些文件处理都可以同时迭代它们。另外,请投入枚举()
以获取行号:使用三个文件:
我得到以下输出:
最后,由于我们没有使用上下文管理器打开原始文件句柄,请记住完成后,请关闭它们:
如果您的文件数量不相等,并且要为 all 行创建文件,请考虑使用
itertools.zip_longest()
而不是使用zip()
Since you have multiple files here, you could define their names in a list, and use a list comprehension to open file handles to them all:
Since each of these file handles is an iterator that yields a single line every time you iterate over it, you could simply
zip()
all these file handles to iterate over them simultaneously. Also throw in anenumerate()
to get the line numbers:With three files:
I get the following output:
Finally, since we didn't use a context manager to open the original file handles, remember to close them after we're done:
If you have files with an unequal number of lines and you want to create files for all lines, consider using
itertools.zip_longest()
instead ofzip()
为了读取每个输入文件,您可以将它们存储在列表中,并用a 用于循环。然后,我们将每行添加到单个列表中,并带有函数
Extend()
:最后,您可以将所有行写入输出文件:
In order to read each of your input files, you can store them in a list and iterate over it with a for loop. Then we add every line to a single list with the function
extend()
:Finally you can write all the line to your output file :