python怎么将0写入文件?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python怎么将0写入文件?相关的知识,希望对你有一定的参考价值。

也许我是傻逼吧
首先我试了
f = open("i.txt","w")
f.write(str(0))
但文件中什么内容也没有
然后我又试了
import os
os.system("echo 0>i.txt")
这时候显示"ECHO处于打开状态"
我该如何将0写入文件呢
(我是小白)

采用上下文模式打开文件

或者强制刷入文件

参考技术A 要将数字0写入文件,可以使用Python内置的文件对象的write()方法将字符串"0"写入文件中。以下是一个示例代码:

with open("file.txt", "w") as f:
f.write("0")
在这个示例中,使用了一个名为"file.txt"的文件,并将其以写入模式打开。然后,使用文件对象的write()方法将字符串"0"写入文件中。最后,使用with语句来自动关闭文件对象。

请注意,write()方法只接受字符串作为参数,因此需要将数字0转换为字符串"0"。如果要将其他数字写入文件,也需要先将其转换为字符串。
参考技术B 注意是字符串!!!!请采纳

可以使用Python的内置函数open()和write()来将0写入文件:
```
with open('filename.txt', 'w') as f:
f.write('0')
```
参考技术C 你的问题在于 str(0) 这个是 NULL呀。
f.write("0") 这样就可以了。
参考技术D f.write("0")
然后记得把文件关闭掉

python怎么将数据写入到redis

参考技术A 代码如下:
import redis

class Database:
def __init__(self):
self.host = 'localhost'
self.port = 6379

def write(self,website,city,year,month,day,deal_number):
try:
key = '_'.join([website,city,str(year),str(month),str(day)])
val = deal_number
r = redis.StrictRedis(host=self.host,port=self.port)
r.set(key,val)
except Exception, exception:
print exception

def read(self,website,city,year,month,day):
try:
key = '_'.join([website,city,str(year),str(month),str(day)])
r = redis.StrictRedis(host=self.host,port=self.port)
value = r.get(key)
print value
return value
except Exception, exception:
print exception

if __name__ == '__main__':
db = Database()
db.write('meituan','beijing',2013,9,1,8000)
db.read('meituan','beijing',2013,9,1)本回答被提问者采纳

以上是关于python怎么将0写入文件?的主要内容,如果未能解决你的问题,请参考以下文章

用java怎么才能在csv文件指定位置写入新的数据,csv原始数据保留。

python 如何将列表写入文件

python中写入中文出错怎么办

python怎么将数据写入txt文件

C语言 把二维数组写入文件?

如何用python将九九乘法表写入csv文件中?