导航:首页 > 编程语言 > python写文件

python写文件

发布时间:2022-01-24 15:20:47

python写文件 写不进去 也不报错

你的写模式错误。用w模式,每次会覆盖原来的,所以,你只会得到最后写入的东西,而你最后写入了一个换行。想要追加写入,用a模式

❷ python怎么以追加的方式写文件

一、用Python创建一个新文件,内容是从0到9的整数, 每个数字占一行:

#python

>>>f=open('f.txt','w') # r只读,w可写,a追加

>>>for i in range(0,10):f.write(str(i)+' ')

. . .

>>> f.close()

二、文件内容追加,从0到9的10个随机整数:

#python

>>>import random

>>>f=open('f.txt','a')

>>>for i in range(0,10):f.write(str(random.randint(0,9)))

. . .

>>>f.write(' ')

>>>f.close()

三、文件内容追加,从0到9的随机整数, 10个数字一行,共10行:

#python

>>> import random

>>> f=open('f.txt','a')

>>> for i in range(0,10):

. . . for i in range(0,10):f.write(str(random.randint(0,9)))

. . . f.write(' ')

. . .

>>> f.close()

四、把标准输出定向到文件:

#python

>>> import sys

>>> sys.stdout = open("stdout.txt", "w")

❸ python 写入文件 只能写入一行

ft=open("a",'w')
try:
ft.write(' '.join(result))
except:
log.error('writebackuperror:'+JOBNAME)
finally:
ft.close()
os.chdir(basePath)

❹ Python如何读写文本文件

1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
2.读文件读文本文件input = open('data', 'r')
#第二个参数默认为r
input = open('data')

读二进制文件input = open('data', 'rb')
读取所有内容file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
读固定字节file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
读每行list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,还可以直接遍历文件对象获取每行:
for line in file_object:
process line
3.写文件写文本文件output = open('data.txt', 'w')
写二进制文件output = open('data.txt', 'wb')
追加写文件output = open('data.txt', 'a')

output .write("\n都有是好人")

output .close( )

写数据file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

❺ python向文件内写入数据

f=open("a.txt","w")
foriinrange(1,10):
f.write("<user> <id>"+str(i)+"</id> </user> ")
f.close()

因为i是int型,所以要先转为str型,再进行字符串拼接,然后写入文件

❻ python文件写操作

这样把
教你个简单的办法
python一般不会在原文件中操作的,一般会读出来,操作,然后再写入的。代码如下:
#encoding:gbk
insert='123'
#你想插入的字符串
line=''
#最终文件内容
f=open("1.txt","r")
i=f.readline()
#读取文件内容
f.close()
pre=i[0:3]
last=i[3:]
line=pre+insert+last
f=open("1.txt","w")
f.write(line)
f.close()

❼ 怎样用python写文件

这个应该打开之后有会有让你让你写字的,然后你就可以把你想写的写上。

❽ python写文件后文件中没有

由于硬盘有缓冲机制,fwrite后数据并没有实际写入到磁盘,而是在缓冲区中,所以这时候打开文件看可能内容是空,需要调用fflush,这时候才能强制把数据写入到文件中,或者调用fclose,文件关闭时数据也会写入到文件中。

阅读全文

与python写文件相关的资料

热点内容
phppython快 浏览:363
pdf转换word免费版 浏览:35
二手的有什么APP 浏览:328
服务器的应用镜像是什么 浏览:151
命令行的使用方法 浏览:511
怎么让图片左右压缩 浏览:653
白鹿原pdf 浏览:431
人民币怎么算法 浏览:756
什么app可以听懂刺猬说话 浏览:600
安卓机内存小如何扩大 浏览:127
粉丝服务器怎么和安卓手机通信 浏览:400
初中数学竞赛pdf 浏览:570
linux自定义安装 浏览:190
fpic要在每个编译文件 浏览:868
编译原理广义推导的定义 浏览:913
怎么在已有的压缩文件里加密码 浏览:519
安卓手机怎么设置系统软件 浏览:768
php前端java后端 浏览:796
数据框转换为矩阵python 浏览:76
单片机程序反汇编 浏览:855