Python学习之文件读取

Python中文件的读取,分为open与with open as file两种。

open和with open as file的区别在于前者去手动调用close关闭文件,而后者会创建一个临时的运行环境,并在代码执行完后自动安全退出环境。

open代码读文件示例:

file =open('D:\demo.txt','r',encoding='utf8');
#读取文件中中所有数据
dataRead=file.read();
print(dataRead)
#读取文件中5个字节
dataNum=file.read(5);
print(dataNum)
#按行读取文件中的所有数据,并封装到列表中
dataLines =file.readlines();
print(dataLines);
#读取文件中一行数据
dataLine=file.readline();
print(dataLine)
#关闭文件
file.close();

with open as file代码读文件示例:

with open('D:\demo.txt','r',encoding='utf8')as file:
    dataRead = file.read();
    print(dataRead)
    # 读取文件中5个字节
    dataNum = file.read(5);
    print(dataNum)
    # 按行读取文件中的所有数据,并封装到列表中
    dataLines = file.readlines();
    print(dataLines);
    # 读取文件中一行数据
    dataLine = file.readline();
    print(dataLine)

Python中对文件的写可使用“w”和“a”,区别:在于对文件的写操作时会覆盖原有的数据信息,而“a”写操作会在原有的数据上进行追加;相同:对于“w”和“a”操作在open文件时,如果文件不存在都会先创建文件,且都会先将数据暂存缓冲区,等待调用close()或fluseh
 

'w'写操作代码:

#打开文件
file = open('D:/PythonDemo/demo.txt', 'w', encoding='UTF-8');
#写入数据
file.write("Hello, world!");
#刷新(此时数据才到文件中)
file.flush();
#关闭文件(携带flush()的)
file.close()


file.writelines(["1","2","3","4","5","6","4"])
file.close();

’a‘写操作代码:

#打开文件
file = open('D:/PythonDemo/demo.txt', 'a', encoding='UTF-8');
#追加数据
file.write("追加数据\n");
#关闭文件(携带flush()的)
file.close()

file.writelines(["1","2","3","4","5","6","4"])
file.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值