[英]combine multiple text files into one text file?
I'm trying to combine multiple files into one, where each of them contains one column and I need to get one file with two columns and plot the resulted file like (x,y) as follows: 我正在尝试将多个文件合并为一个,其中每个文件包含一列,而我需要获取一个包含两列的文件,并绘制结果文件,如(x,y),如下所示:
x y result
1 4 1 4
2 5 2 5
3 6 3 6
and run the code for n
text files. 并运行n
文本文件的代码。
How can I do this? 我怎样才能做到这一点?
here's a quick-and-dirty solution. 这是一个快速而又肮脏的解决方案。 I assumed that all files have the exact number of rows. 我假设所有文件都有确切的行数。 The function write_files
gets an input files
which is a list of file-paths (strings). 函数write_files
获取输入files
,该files
是文件路径(字符串)的列表。
def write_files(files):
opened_files = []
for f in files:
opened_files.append(open(f, "r"))
output_file = open("output.txt", "w")
num_lines = sum(1 for line in opened_files[0])
opened_files[0].seek(0,0)
for i in range(num_lines):
line = [of.readline().rstrip() for of in opened_files]
line = " ".join(line)
line += "\n"
output_file.write(line)
for of in opened_files:
of.close()
output_file.close()
write_files(["1.txt", "2.txt"])
A simple solution assuming that all files have the same number of elements in float format. 一个简单的解决方案,假设所有文件的浮点格式的元素数量均相同。
import numpy as np
filename_list=['file0.txt', 'file1.txt']#and so on
columns = []
for filename in filename_list:
f=open(filename)
x = np.array([float(raw) for raw in f.readlines()])
columns.append(x)
columns = np.vstack(columns).T
np.savetxt('filename_out.txt', columns)
see also the method savetxt to customize the output 另请参见方法savetxt以定制输出
EDIT: if you have 100 files in a certain directory (let's call it files_dir
) you can use the method listdir
in the os
library, be be careful, since listdir
returns directories and files: 编辑:如果您在某个目录中有100个文件(我们称其为files_dir
),则可以使用os
库中的listdir
方法,请小心,因为listdir
返回目录和文件:
import os
filename_list = [f for f in os.listdir(files_dir) if os.path.isfile(f)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.