我正在编写一个脚本来分析一些实验数据,然后将某些信息输出到一个文本文件。该文本文件由另一个应用程序使用,该应用程序无法理解 \n 标记,并且我无法删除 \n 标记。如何在没有 \n 标记的情况下写入文本文件?
对 Python 来说相对较新。
我知道在没有 \n 的情况下用 Python 读取文件会成为一个问题(总是这样吗?你不能读取其他应用程序创建的文本文件吗?)但如果有必要,我已经想到了一种解决方法。
##Create MAPDL material data text file
file = open('MAPDL_material.txt', 'w')
file.write('TB, MELAS')
file.close()
def MAPDL_add_line(j,MAPDL_strain,MAPDL_stress): # Definition to add data to text file
# Add text to first line (requires to open, read, and completely rewrite)
file = open('MAPDL_material.txt', 'r')
file_text = file.readlines()
file.close()
file_text[0] = file_text[0] + ',' + str(j)
file = open('MAPDL_material.txt', 'w')
for i in file_text:
file.write(i + "/n")
file.close()
# Append line to end of file for new datapoint
file = open('MAPDL_material.txt', 'a')
file.write('TBPT, ,'+str(MAPDL_strain)+','+str(MAPDL_stress))
file.close()
print('Row '+str(j)+' added to MAPDL material file.')
问题是文本文件是这样的:
TB, MELAS,1/nTBPT, ,0.005,33
但需要这样,其他应用程序才能读取它:
TB, MELAS,1
TBPT, ,0.005,33