如何将文件的每行保存到新文件(每行新文件)并为多个原始文件执行此操作

发布于 2025-02-05 19:03:32 字数 619 浏览 2 评论 0 原文

我有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的初学者,我不确定如何为此循环,因为我认为我需要一个循环?

谢谢你!

I have 5 files from which i want to take each line (24 lines in total) and save it to a new file. I managed to find a code which will do that but they way it is, every time i have to manually change the number of the appropriate original file and of the file i want to save it to and also the number of each line every time.

The code:

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)

I am a beginner at python, and i'm not sure how to make a loop for this, because i assume i need a loop?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

假扮的天使 2025-02-12 19:03:32

由于您在这里有多个文件,因此您可以在列表中定义其名称,并使用列表理解为所有文件打开所有内容:

input_files = ["x_p2_40.txt", "x_p4_40.txt", "x_p6_40.txt", "x_p8_40.txt", "x_p1_40.txt"]

file_handles = [open(f, "r") for f in input_files]

由于这些文件句柄中的每一个都是一个迭代器,每次迭代它都会产生一条线路,您可以简单地 zip()所有这些文件处理都可以同时迭代它们。另外,请投入枚举()以获取行号:

for line_num, files_lines in enumerate(zip(*file_handles), 1):
    out_file = f"{line_num}_p_40.txt"
    # Remove trailing whitespace on all lines, then add a newline
    files_lines = [f.rstrip() + "\n" for f in files_lines] 
    with open(out_file, "w") as of:
        of.writelines(files_lines)

使用三个文件:

x_p2_40.txt:
2_1
2_2
2_3
2_4

x_p4_40.txt:
4_1
4_2
4_3
4_4

x_p6_40.txt:
6_1
6_2
6_3
6_4

我得到以下输出:

1_p_40.txt:
2_1
4_1
6_1

2_p_40.txt:
2_2
4_2
6_2

3_p_40.txt:
2_3
4_3
6_3

4_p_40.txt:
2_4
4_4
6_4

最后,由于我们没有使用上下文管理器打开原始文件句柄,请记住完成后,请关闭它们:

for fh in file_handles:
    fh.close()

如果您的文件数量不相等,并且要为 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:

input_files = ["x_p2_40.txt", "x_p4_40.txt", "x_p6_40.txt", "x_p8_40.txt", "x_p1_40.txt"]

file_handles = [open(f, "r") for f in input_files]

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 an enumerate() to get the line numbers:

for line_num, files_lines in enumerate(zip(*file_handles), 1):
    out_file = f"{line_num}_p_40.txt"
    # Remove trailing whitespace on all lines, then add a newline
    files_lines = [f.rstrip() + "\n" for f in files_lines] 
    with open(out_file, "w") as of:
        of.writelines(files_lines)

With three files:

x_p2_40.txt:
2_1
2_2
2_3
2_4

x_p4_40.txt:
4_1
4_2
4_3
4_4

x_p6_40.txt:
6_1
6_2
6_3
6_4

I get the following output:

1_p_40.txt:
2_1
4_1
6_1

2_p_40.txt:
2_2
4_2
6_2

3_p_40.txt:
2_3
4_3
6_3

4_p_40.txt:
2_4
4_4
6_4

Finally, since we didn't use a context manager to open the original file handles, remember to close them after we're done:

for fh in file_handles:
    fh.close()

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 of zip()

jJeQQOZ5 2025-02-12 19:03:32

为了读取每个输入文件,您可以将它们存储在列表中,并用a 用于循环。然后,我们将每行添加到单个列表中,并带有函数 Extend()

inputFiles = ["x_p2_40.txt", "x_p4_40.txt", "x_p6_40.txt", "x_p8_40.txt", "x_p1_40.txt"]
outputFile = "outputfile.txt"

lines = []
for filename in inputFiles:
    with open(filename, 'r') as f:
        lines.extend(f.readlines())
        lines[-1] += '\n' 

最后,您可以将所有行写入输出文件:

with open(outputFile, 'w') as f:
    f.write(''.join(lines))

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() :

inputFiles = ["x_p2_40.txt", "x_p4_40.txt", "x_p6_40.txt", "x_p8_40.txt", "x_p1_40.txt"]
outputFile = "outputfile.txt"

lines = []
for filename in inputFiles:
    with open(filename, 'r') as f:
        lines.extend(f.readlines())
        lines[-1] += '\n' 

Finally you can write all the line to your output file :

with open(outputFile, 'w') as f:
    f.write(''.join(lines))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文