Python对文件操作知识汇总
打开文件
操作文件
1打开文件时,需要指定文件路径和打开方式
打开方式:
r:只读
w:只写
a:追加
“+”表示可以同时读写某个文件
r+:读写
w+:写读
a+:同a
U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
rU
r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
rb
wb
ab
f = open('test.log','r+',encoding='utf-') f.write('saf中sdhgrbfds') print(f.tell()) #查看当前指针位置,以字符为单位 f.seek() #指定当前指针位置,以字节为单位 print(f.read()) f.truncate() #读取指针之前的数据 print(f.tell()) f.close()
二:常见的文件运算
f = open('data', 'r') #以只读形式打开(默认就是只读)
f = open('f.txt', encoding='latin-1') #python3.0 Unicode文件
string = f.read() #把文件读入一个字符串中
string = f.read(N) #读取指针后的N个字节
string = f.readline() #读取下一行,包括行末标识符
alist = f.readlines() #读取整个文件到字符串列表
f.write() #将字符串写入文件
f.writelines() #将列表内所有字符串写入文件
f.close() #手动关闭
f.flush() #把输出缓冲区刷到硬盘中
f.seek(N) #将文件指针移到N处,以字节为单位
for line in open('data'):
print(line) #文件迭代器将文件一行行读出
open('f.txt','r').read() #read all at ance into string
三:在文件中存储并解析python对象
x,y,z = 41,42,43 s = 'spam' D = {'a':1, 'b':2} #字典对象 L = ['a','b','c'] #列表 f = open('f.txt','w') f.write(s + '\n') f.write('%s,%s,%s\n'%(x,y,z)) f.write(str(D)) f.write('\n') f.write(str(L)) f.close() print(open('f.txt').read()) #将文件内容输出 #从文件中取出数据,并判断其类型 ''' a = fi.readline() b = fi.readline() c = fi.readline() d = fi.readline() print(a,b,c,d,type(a),type(b),type(c),type(d)) ''' # 从文件中取出数据,并转换为存储前的类型 fi = open('f.txt') a = fi.readline().rstrip() #rstrip()去掉换行符 print(a,type(a)) b = fi.readline().rstrip().split(',') #字符串的split()方法,在括号中写入分隔符,将字符串分割为列表。 print(b,type(b)) c = fi.readline() C = eval(c) #调用内置函数eval(),将字符串转化为可执行的python代码。 print(C,type(C),type(c)) d = fi.readline() D = eval(d) print(D,type(D),type(d))
以上所述是小编给大家介绍的Python对文件操作知识汇总的相关知识,希望对大家有所帮助!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.
