[英]Writing a text file error using python 3.x “with open” function
I am writing a text file with some of the data I analyzed using python. 我正在编写一个文本文件,其中包含我使用python分析的一些数据。 I am running into some error messages. 我遇到了一些错误消息。 Below is my code. 下面是我的代码。
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)
What I want in my text file is the following 我想要的文本文件如下
16+,0.1
15+,0.3
14+,-.4
14-,1
13-,2
The error message I get is the following. 我收到的错误消息如下。
ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32').
I thought I understood with open
function. 我以为我了解with open
功能。 Your suggestions will be greatly appreciated. 您的建议将不胜感激。 Any suggestions? 有什么建议么?
It has nothing to do with open()
and its context manager, it has to do with the concatenation of your data and mismatched types. 它与open()
及其上下文管理器无关,它与数据和类型不匹配的串联有关。 Your example, tho, should throw a different error - I imagine the error you posted stems from some Pandas structure. 您的示例tho应该引发另一个错误-我想象您发布的错误源于某些Pandas结构。
You can let str.format()
attempt to concatenate your data as: 您可以让str.format()
尝试将数据串联为:
with open('TMV_AVD.txt', 'w') as f:
f.write('16+,{}\n15+,{}\n14+,{}\n14-,{}\n13-,{}'.format(sixteen, fifteen, fourteen,
fourteen_revised, thirteen))
Or, if using Python 3.6+ you can directly build an f string : 或者,如果使用Python 3.6+,则可以直接构建f字符串 :
f.write(f"16+,{sixteen}\n15+,{fifteen}\n14+,{fourteen}\n14-,{fourteen_revised}\n13-,{thirteen}")
Or you'll have to manually turn your data into a proper format before concatenating. 或者,您必须在连接之前手动将数据转换为正确的格式。
Your logic is overly complicated. 您的逻辑过于复杂。 I strongly recommend you use a list of tuples or OrderedDict
to store your variables. 我强烈建议您使用元组列表或OrderedDict
来存储变量。 Then use a simple for
loop: 然后使用一个简单的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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.