我正在尝试修改要由软件重新处理的原始数据 .txt 文件。问题是,该软件需要数据表之前的文本文件中的附加参数。因此,df.to_csv
覆盖我需要的行。
字符串方法是成功的,但不允许我使用'\t'
分隔符
#Building example dataframe
index = [0,1,2,3,4,5]
t = pd.Series([2,6,9,8,10,12],index= index)
s = pd.Series([7,2,6,8,5,9],index= index)
df = pd.DataFrame({'Time (s)':t,'X Position':x})
file="C:/Users/user/Desktop/example.txt"
f = open(file, "w")
f.write(f"Multiple\nlines\ngo here\n\n")
f.close()
with open(file, 'a') as f:
dfAsString = df.to_string(index=False)
f.write(dfAsString)
f.close()
这给出了以下 .txt 输出:
Multiple
lines
go here
Time (s) X Position
2 7
6 2
9 6
8 8
10 5
12 9
我需要将此数据框添加到文件中,但还需要将输出用制表符分隔,而不影响上面的文本。非常欢迎帮助。
您可以使用 to_csv 将新数据框(制表符分隔)附加到现有文件:
file="example.txt"
f = open(file, "w")
f.write(f"Multiple\nlines\ngo here\n\n")
f.close()
df.to_csv(file, mode='a', index=False, header=True, sep = "\t")
这个的输出是:
Multiple
lines
go here
Time (s) X Position
2 7
6 2
9 6
8 8
10 5
12 9
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句