使用python3.x"with open"函数写入文本文件错误
Writing a text file error using python 3.x "with open" function
我正在用 python 分析的一些数据编写一个文本文件。我 运行 收到一些错误消息。下面是我的代码。
sixteen=0.1
fifteen=0.3
fourteen=-.4
fourteen_revised=1
thirteen=2
with open('TMV_AVD.txt','w') as f:
f. write('16+',sixteen+'\n','15+', fifteen+'\n','14+',\
fourteen+'\n','14-',fourteen_revised+'\n', '13-', thirteen)
我想要的文本文件如下
16+,0.1
15+,0.3
14+,-.4
14-,1
13-,2
我得到的错误信息如下。
ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32').
我以为我理解了with open
函数。您的建议将不胜感激。有什么建议么?
它与 open()
及其上下文管理器无关,它与您的数据和不匹配类型的串联有关。你的例子应该抛出一个不同的错误 - 我想你发布的错误源于某些 Pandas 结构。
您可以让 str.format()
尝试将您的数据连接为:
with open('TMV_AVD.txt', 'w') as f:
f.write('16+,{}\n15+,{}\n14+,{}\n14-,{}\n13-,{}'.format(sixteen, fifteen, fourteen,
fourteen_revised, thirteen))
或者,如果使用 Python 3.6+,您可以直接构建一个 f 字符串:
f.write(f"16+,{sixteen}\n15+,{fifteen}\n14+,{fourteen}\n14-,{fourteen_revised}\n13-,{thirteen}")
或者您必须在连接之前手动将数据转换为正确的格式。
你的逻辑太复杂了。我强烈建议您使用元组列表或 OrderedDict
来存储您的变量。然后使用一个简单的 for
循环:
d = [('sixteen', ('16+', '0.1')),
('fifteen', ('15+', '0.3')),
('fourteen', ('14+', '-.4')),
('fourteen_revised', ('14-', '1')),
('thirteen', ('13-', '2'))]
with open('TMV_AVD.txt', 'w') as f:
for _, vals in d:
f.write(','.join(vals)+'\n')
我正在用 python 分析的一些数据编写一个文本文件。我 运行 收到一些错误消息。下面是我的代码。
sixteen=0.1
fifteen=0.3
fourteen=-.4
fourteen_revised=1
thirteen=2
with open('TMV_AVD.txt','w') as f:
f. write('16+',sixteen+'\n','15+', fifteen+'\n','14+',\
fourteen+'\n','14-',fourteen_revised+'\n', '13-', thirteen)
我想要的文本文件如下
16+,0.1
15+,0.3
14+,-.4
14-,1
13-,2
我得到的错误信息如下。
ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32').
我以为我理解了with open
函数。您的建议将不胜感激。有什么建议么?
它与 open()
及其上下文管理器无关,它与您的数据和不匹配类型的串联有关。你的例子应该抛出一个不同的错误 - 我想你发布的错误源于某些 Pandas 结构。
您可以让 str.format()
尝试将您的数据连接为:
with open('TMV_AVD.txt', 'w') as f:
f.write('16+,{}\n15+,{}\n14+,{}\n14-,{}\n13-,{}'.format(sixteen, fifteen, fourteen,
fourteen_revised, thirteen))
或者,如果使用 Python 3.6+,您可以直接构建一个 f 字符串:
f.write(f"16+,{sixteen}\n15+,{fifteen}\n14+,{fourteen}\n14-,{fourteen_revised}\n13-,{thirteen}")
或者您必须在连接之前手动将数据转换为正确的格式。
你的逻辑太复杂了。我强烈建议您使用元组列表或 OrderedDict
来存储您的变量。然后使用一个简单的 for
循环:
d = [('sixteen', ('16+', '0.1')),
('fifteen', ('15+', '0.3')),
('fourteen', ('14+', '-.4')),
('fourteen_revised', ('14-', '1')),
('thirteen', ('13-', '2'))]
with open('TMV_AVD.txt', 'w') as f:
for _, vals in d:
f.write(','.join(vals)+'\n')