【发布时间】:2016-05-24 16:17:52
【问题描述】:
我正在尝试将多个 .txt 文件合并到一个文件中。有些文件是我预先创建的纯文本 .txt 文件,而有些是脚本本身编写的文件。该脚本成功地合并了一些文件(我预先编写的那些),但不包括脚本创建的文件,即使它没有引发错误。从字面上看,它似乎忽略了它们的存在。
我尝试了不同的方法,包括shutil 和fileinput,甚至使用subprocess.call 中的cat,但都没有运气。
从终端看,我预先创建的文件是“XML文档文本”(虽然我实际上保存为纯文本,但它是格式化为XML),而其他文件是“ASCII文本”。我相信这是问题所在,因为 XML 文件是 .rtf 文件,在我转换它们之前它们不会合并 - 只有列表中的第一个会包含在输出文件中。
import os, itertools, subprocess, fileinput, shutil
os.chdir('/Users/MicTonutti/Dropbox/MRes/Individual Project/FEBio/Simulation')
forces = itertools.permutations([-1.5,-1,-0.5,0],3)
forces = list(forces)
force_node = 174
for i in range(0,len(forces)):
filename = '0_Insert' + str(i) + '.txt'
f = open(filename, 'w')
string_x = '<nodal_load bc="x" lc="2"> <node id="' + str(force_node) + '">' + str(forces[i][1]) + '</node> </nodal_load>\n'
string_y = '<nodal_load bc="y" lc="2"> <node id="' + str(force_node) + '">' + str(forces[i][2]) + '</node> </nodal_load>\n'
string_z = '<nodal_load bc="z" lc="2"> <node id="' + str(force_node) + '">' + str(forces[i][2]) + '</node> </nodal_load>\n'
f.write(string_x + string_y + string_z)
filename_2 = '1_Insert' + str(i) + '.txt'
g = open(filename_2, 'w')
string_1 = '<logfile>\n <node_data data="x;y;z" file = "coord_data' + str(i) + '.txt" delim=", "> </node_data>\n'
string_2 = '<node_data data="ux;uy;uz" file = "displacement_data' + str(i) + '.txt" delim=", "> </node_data>\n </logfile>\n'
g.write(string_1 + string_2)
files_list = ['Simulation 1.txt', filename, 'Simulation 2.txt', filename_2, 'Simulation 3.txt']
output_file = '/Users/MicTonutti/Dropbox/MRes/Individual Project/FEBio/Simulation/Python Output/FEBio Simulation Output' + str(i) + '.txt'
with open(output_file, 'w') as outfile:
for infile in files_list:
shutil.copyfileobj(open(infile), outfile)
输出基本上是这样的:
“Simulation1.txt”文本+“Simulation2.txt”文本+“Simulation3.txt”文本,中间没有文件。 有什么想法吗?
谢谢。
【问题讨论】: