A. python 文件读写
你的filename是多少,看提示貌似是你的文件不存在活着路径错误
B. 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( )
C. 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()
D. python向文件内写入数据
f=open("a.txt","w")
foriinrange(1,10):
f.write("<user> <id>"+str(i)+"</id> </user> ")
f.close()
因为i是int型,所以要先转为str型,再进行字符串拼接,然后写入文件
E. python中打开文件再写入的两种方式的区别
没有区别;
均为可读可写。
如果文件不存在就创建一个新文件。
看你习惯用哪种
F. python文件读写
这两个问题都是由于最后一句使用了to_excel导致的,改成to_csv即可
另外,to_csv可以生成csv或者xls文件。
改成:data.to_csv(cleanedfile,sep="\t", encoding="utf-8")
G. PYTHON写文件 写不进去 也不报错
你的写模式错误。用w模式,每次会覆盖原来的,所以,你只会得到最后写入的东西,而你最后写入了一个换行。想要追加写入,用a模式
H. 怎样用python写文件
这个应该打开之后有会有让你让你写字的,然后你就可以把你想写的写上。
I. 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")
J. 关于python里写文件的操作
fo.close()---你小括号没有。
fo = open("D:/text一.txt","w",encoding = 'utf-8')
ls = ['13','14','15']
fo.writelines(ls)
fo.close()
文件在d盘下面