search
HomeBackend DevelopmentPython TutorialPython对文件操作知识汇总

打开文件

操作文件

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对文件操作知识汇总的相关知识,希望对大家有所帮助!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment