搜索
首页后端开发Python教程Python自学文件操作

Python自学文件操作

Dec 16, 2020 pm 05:44 PM
python文件操作

python视频教程栏目介绍自学文件操作

Python自学文件操作

推荐(免费):python视频教程

我是一个学习Python初学者,近期刚学完文件操作。特地分享
文章分为两部分,第一部分为文件读取类型以及读取的方式,第二部分为练习题

文件读取类型

文件读取的操作方式有以下几种:只读,只写,追加,读写,写读

只读    r

f = open('test',mode='r',encoding='utf-8')  # 打开文件,读取方式为`r`,编码为UTF-8
f1 = f.read() # 读取文件
print(f1) #打印文件
f.close() # 关闭文件

只读类型下,文件不能被修改

读写 r+

f = open('test',mode='rb',encoding='utf-8') # 读取方式变为`r+`
file = f.read()
f1 = f.read()
f.close()

当读取方式为r+时,文件可以被写入,但是打印出来的是写入前所读取的

二进制读 rb
代码略去,文件以二进制的模式读取。

剩下的我将以表格形式统一展现,可以参照对比以上代码

读取方式 补充
r 只读,不可被修改
r+ 读写,光标在前,从第一个位置开始修改,打印出修改的字符数
rb byte方式读取
w 只写,若写入的目标文件没有,则创建,有则清空再写入
wb 转换为byte类型写入
a 打开文件,把光标移动到有文字的后面,再进行追加
ab byet类型加入

:r+有两个表现,一个是读写,还有一个是写读。需要注意。另,w+a+我没有写,是因为学习阶段用的相对来说较少

读取功能

我先以表格形式展示,再进行详解

读取方式 用于场合
read() 以字符读,可添加参数(I),读前i个字符
seek() 调整光标位置
tell() 调整光标位置,需放置于seek()
readline() 一行一行的读
readlines() 将每一行当成列表中元素读取,换行自带 \n
truncate() 截取一段读出来,从后往前读

例如有一个名为test的文件,文件内容如下:

456926667

这是一个长为10个字符的字符串

f = open('test',mode='r',encoding='utf-8')  # 打开文件,读取方式为`r`,编码为UTF-8
f1 = f.read(5) # 读取文件中前5个字符
print(f1) #打印文件
f.close() # 关闭文件

打印结果为

45692

f = open('test',mode='w',encoding='utf-8')  # 打开文件,读取方式为`w`,编码为UTF-8
f1 = f.seek()
print(f1) #打印第五个字符
f.close() # 关闭文件

打印结果为

2

剩下的我就不一一做演示,有需要可以自己试一试

文件读取方式

f = open('test',mode='w',encoding='utf-8')

此文件读取方式,仅能读取一个文件,另外代码多

with open('test',mode='w',encoding='utf-8') as f:
      pass

此文件读取方式,能同时读取多个文件,且代码量相对来说少

当需要同时操作两个或两个文件以上时,with open 方法会相对来说简易许多

以上是Python自学文件操作的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:简书。如有侵权,请联系admin@php.cn删除
可以在Python数组中存储哪些数据类型?可以在Python数组中存储哪些数据类型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python标准库的哪一部分是:列表或数组?Python标准库的哪一部分是:列表或数组?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您应该检查脚本是否使用错误的Python版本执行?您应该检查脚本是否使用错误的Python版本执行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!