随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

读取/写入文件

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
复制代码

 

posted on   momingliu11  阅读(642)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示