读取/写入文件
print([arg],end='\n'),默认以换行符结尾,等价于 print([arg]),输出会添加一个空行。如果去掉空行,则可以 print([arg],end=''),可以对end赋予任何值
读取文件:
#直接读取
for line in open("d:\serverlist.txt"):
print(line)
#使用readline()方法读取
file = open('d:\serverlist.txt')
line = file.readline()
while line:
print(line,end=‘’)
file.close()
#使用read()方法读取
f = open("d:\out.txt",'r')
mm=f.read()
f.close()
print(mm)
写入文件:
#新建或覆盖原文件写入
f = open("d:\out.txt", 'w')
print("abc",file=f)
f.close()
#追加写入
f = open("d:\out.txt", 'a')
print("abcdef",file=f)
f.close()
#使用write()方法写入
f = open("d:\out.txt",'a')
f.write("\nnnnn")
f.close()
读取并输出:
result = open('d:\\rr.txt','a')
for line in open('d:\\serverlist.txt','r'):
#result.write(line) #方法一
print(line,file=result,end='') #方法二
result.close()
for line in open('d:\\serverlist.txt','r'):
print(line.replace('\n','') + "nihao") #在每行后面添加字符串“nihao,需要替换掉换行符”
=============================================================
#读文件 f2=open("filew.txt","r") f2.read(10) #读取前10个字符
f2.readline() #读一行
f2.readline(2) #读一行中的前两个字符
f2.readlines(2) #读两行
f2.readlines() #读所有行
f2.tell() #显示当前指针位置 f2.seek(0,0) #将指针移动到文件开始位置 for i in f2: #读取文件内容并打印 print i #读文件2: for i in open("filew.txt"): print i+ "hello" #写入文件,不存在则新建,否则覆盖,w模式打开文件时,内容会被清空 f1 =open("filew.txt","w") f1.write("hello\ni89\n00") f1.close() #追加写入 f1 =open("filew.txt","a") f1.write( "\nPython is a great language.\nYeah its great!!\n") f1.close()
#读取文件: for i in open('pp.txt'):print i 返回(带有换行符号): zhangsan,18,male lisi,20,male xiaohong,22,female xiaoli,25,female wangwu,25,male #读取文件,去掉换行符号: for i in open('pp.txt'):print i.strip() 返回: zhangsan,18,male lisi,20,male xiaohong,22,female xiaoli,25,female wangwu,25,male
with语句自动调用close() with open('/Users/michael/test.txt', 'w') as f: f.write('Hello, world!') with open('/path/to/file', 'r') as f: print f.read() 同下: try: f = open('/path/to/file', 'r') print f.read() finally: if f: f.close()
with open('e:\\a.txt','rb') as f: for i in f: #默认按行读取 print i.strip()
#每次读取固定大小字节 fpath = 'e:\\a.txt' def fread(fpath,blocksize=4): with open(fpath,'rb') as f: while True: rc = f.read(blocksize) if rc: yield rc else: break fr=fread(fpath) for i in fr: print i