文件操作

#文件操作
#打开一个文件:
# open("文件名""打开模式")
# with open("文件名",'打开模式") as 给文件定义变量名:
#文件方法:
# file.closes() 关闭文件
# file.closed 判断文件是否关闭
# file.seek(移动字节数) 以字节形式移动光标
# file.name 查看文件名字
# file.tell() 查看光标位置
#文件的打开模式
# r 只读模式,如果文件不存在则返回异常
# w 覆盖写模式,如果文件存在则覆盖,不存在则新建
# + r/w/x/a,一起使用,在原有功能基础上增加读写功能
# a 追写模式,文件不存在返回异常,存在则在文件后面追加内容
# t 文本文件模式
# b 二进制文本模式
# x 创建写模式,文件不存在则返回异常,存在则创建
#文件内容的读取方法:
# file.readable() 判断文件是否可读,可读则返回True
# file.readlines() 读入文件所有内容,以每行元素形成一个列表
# file.readline() 每次读入一行内容
# file.read() 从文件中读入整个内容
# file.close() 关闭文件
#文件内容的写入方法:
# file.write(str)
# file.writelines([str])
# file.writable() 判断是否为写模式,如果是返回True,否则返回False

#
# #读操作

f = open('文件操作.txt ','r+',encoding='UTF-8')

print(f.read()) #从文件中读入整个文件内容

print(f.readable()) #返回Truereadable()判断文件是否可读,如果可读返回True,否则返回False

def show():
if f.readable() == False:
print("这个文件不可读")
else:
print("这个文件可读")
show()

print(f.readline()) #每次从文件中只读取一行

print(f.readlines()) #从文件中读入所有内容,以每行元素形成一个列表

f.close() #关闭文件

print('------------------读操作--end-------------------')

#写操作

f = open('文件操作.txt','r+',encoding='UTF-8')
print('-------------->新的输入:')
f.write('the today is very good fjkdfjdkjfld sfjdklfjd ') #必须传入字符串

print(f.writable()) #判断是否是写模式

li = ['a','b','c','d','e',]
def panduan():
if f.writable() == True:
f.write(str(li))
print('写入成功')
else:
print("请转换为写模式,在进行写操作")
panduan()
print('-----------------f--end---------------')

f.writelines([' dfjlfjldkfj,dfddf']) #可以传入字符串也可以传入可迭代对象
print(f.name) #输出文件的名称
f.close()

#追写模式的使用
x = open('文件操作.txt ','a',encoding='UTF-8')
x.write(' 这是追加的内容')
x.close()
print('------------追写模式--end---------')

#文件的打开模式2
with open('文件操作.txt ','r',encoding='UTF-8') as x_1:
print(x_1.read())

print('---------x_1--end----------')

#可以利用这种形式复制文件内容
with open('1.txt','r',encoding='utf-8') as x_2,open('2.txt','w',encoding='utf-8') as x_3:
x_3.write(x_2.read())

print('---------x_2--x_3--end----------')

x_4 = open('2.txt','r',encoding='utf-8',newline='') #读取文件中真正的换行符号
#x_4.close()
def panduan_2(): #判断文件是否关闭,是则返回True否则返回False
if x_4.closed == True:
print('文件已关闭')
else:
print('文件未关闭')
panduan_2()
print(x_4.encoding) #获取文件打开编码
print(x_4.flush()) #刷新
print('--------x_4--end----------')

#文件中光标的位置
with open('2.txt ','r+',encoding='utf-8') as x_5:
x_5.seek(110) #控制光标以字节移动
print(x_5.tell()) #文件中光标的位置
x_5.write('鼠标位于第110个字节')
x_5.close()

print('---------x_5--end----------')

x_6 = open('1.txt','r+',encoding='utf-8')
x_6.truncate(10) #截取内容


print('---------x_6--end----------')
原文地址:https://www.cnblogs.com/shadowfolk/p/14674822.html