关于文件操作的方法

#追加方式打开文件
#f = open('young.txt','a')
#只读方式打开文件
#f = open('young.txt','r')
#data = f.readlines()
#data = f.readline()
#print(data)
#以读写方式打开文件
'''
f = open('young.txt','r+')
print(f.readline())
print(f.readline())
f.write('######################') #确保文件没有存在,如果存在,则会首先清空,然后写入。
print(f.readline())
'''
#以写读方式打开文件
'''
f = open('young.txt','w+')
print(f.readline())
print(f.readline())
print(f.tell())
f.seek(10)
f.write('######################')
print(f.readline())
'''
#二进制文件读写

#f = open('young.txt','rb')
#f = open('young.txt','wb')
#print(f.readline())
#f.write('Hello binary
'.encode())
#f.close()
'''
'''


#不打印指定的某一行,效率较低,读的每一行都在内存中
'''
f = open('young.txt','r')
lines = f.readlines()

for index,line in enumerate(lines):
    if index == 2:
        print('我是分割线'.center(50,'*'))
        continue
    else:
        print(line.strip()) #去掉空格及换行
'''
#高效读取文件
'''
f = open('young.txt','r')
for line in f:
    print(line.strip())
print(type(f))

'''
#光标回到文件的开始
'''
f = open('young.txt','r')
f.readline()
f.readline()
print(f.tell()) #告诉光标位置
f.seek(0) #光标回到文件开始
print(f.readline())
f.close()


f = open('young.txt','r',encoding='utf-8')
print(f.encoding) #打印文件字符编码
print(f.fileno()) #打印文件在内存中的编号
print(f.name) #打印文件名
print(f.truncate(10)) #截断文件内容


#文件修改 讲旧文件中的内容一行一行读出,进行修改,然后写到新文件中
f = open('young.txt','r')
f_new = open('newyoung.txt','w')
for line in f:
    if '我' in line:
        line = line.replace('我','Akuma')
    f_new.write(line)
    f_new.flush()
f.close()
f_new.close()


#文件用with打开,不需close语句
with open('young.txt','r') as f:
    for line in f:
        print(line)

'''
View Code
原文地址:https://www.cnblogs.com/AkumaIII/p/8078642.html