导航:首页 > 编程语言 > 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写文件相关的资料

热点内容
中国没有国外的服务器地址 浏览:757
为什么退款服务器连接错误 浏览:555
android短信存储位置 浏览:970
unix网络编程卷4 浏览:806
找靓机app下单什么时候发货 浏览:412
android一个应用两个进程 浏览:801
linux硬盘复制 浏览:808
php图片服务器搭建 浏览:801
下载压缩文件怎么打开 浏览:194
新建文件夹叫什么名字 浏览:567
windows20的开机命令 浏览:334
微信一般在电脑的那个文件夹 浏览:511
go在win7下编译特别慢 浏览:256
光遇ios耳机安卓为什么没有 浏览:904
小米手机桌面文件夹经常自动散开 浏览:607
小米电话手表用什么app进行设置 浏览:265
虚拟打印机pdf下载 浏览:671
jdk编译运行方法 浏览:459
android执行shell命令 浏览:349
程序员头像女 浏览:57