【问题标题】:Cannot merge .txt files having different encoding in Python无法在 Python 中合并具有不同编码的 .txt 文件
【发布时间】:2016-05-24 16:17:52
【问题描述】:

我正在尝试将多个 .txt 文件合并到一个文件中。有些文件是我预先创建的纯文本 .txt 文件,而有些是脚本本身编写的文件。该脚本成功地合并了一些文件(我预先编写的那些),但不包括脚本创建的文件,即使它没有引发错误。从字面上看,它似乎忽略了它们的存在。

我尝试了不同的方法,包括shutilfileinput,甚至使用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”文本,中间没有文件。 有什么想法吗?

谢谢。

【问题讨论】:

    标签: python xml merge ascii


    【解决方案1】:

    您应该在尝试再次读取之前对您写入的文件调用flush(),否则写入的数据可能仍会被缓冲。

    除此之外,我想指出您在循环中写入了 24 个不同的 0_Insert 文件(0_Insert1.txt0_Insert23.txt),但后来只读取最后一个文件。这是你真正想要做的吗?还是你的循环也应该包括代码的底部?

    【讨论】:

    • 是的,抱歉——我的代码在复制粘贴后格式错误。 for 循环包括直到结束的所有内容。无论如何,flush() 完美地工作!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2020-03-07
    • 1970-01-01
    • 2021-10-04
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多