Python文件读写6大实用方法小结!
Python文件读写6大实用方法小结!
Python文件读写的6大实用方法涵盖了从基本读取到高级操作的不同场景。以下是这些方法的具体介绍:
一、使用open函数读取文件
这是Python中读取文件最基本的方式。使用open
函数以只读模式(‘r’)打开文件,并指定文件编码(如’utf-8’)。然后,可以使用文件对象的read
方法一次性读取整个文件内容。
1
2
3
|
with open ( 'example.txt' , 'r' , encoding = 'utf-8' ) as file : content = file .read() print (content) |
二、按行读取文件
对于大文件,一次性读取全部内容可能会消耗大量内存。因此,按行读取是一个更好的选择。使用for
循环逐行读取文件内容,并使用strip
方法去除每行末尾的换行符。
1
2
3
|
with open ( 'example.txt' , 'r' , encoding = 'utf-8' ) as file : for line in file : print (line.strip()) |
三、写入文件
使用open
函数以写入模式(‘w’)或追加模式(‘a’)打开文件。然后,可以使用文件对象的write
方法将字符串写入文件。在’w’模式下,如果文件已存在,其内容会被清空;在’a’模式下,新内容会被追加到文件末尾。
1
2
3
4
5
6
7
8
|
# 写入文件 with open ( 'output.txt' , 'w' , encoding = 'utf-8' ) as file : file .write( 'Hello, Python!\n' ) file .write( 'Welcome to file operations.\n' ) # 追加内容到文件 with open ( 'output.txt' , 'a' , encoding = 'utf-8' ) as file : file .write( '\nGoodbye, Python!' ) |
四、使用readlines读取所有行
readlines
方法会读取文件中的所有行,并返回一个包含每行内容的列表。每个列表元素代表文件中的一行。
1
2
3
4
|
with open ( 'example.txt' , 'r' , encoding = 'utf-8' ) as file : lines = file .readlines() for line in lines: print (line.strip()) |
五、使用writelines写入多行内容
writelines
方法接受一个字符串列表作为参数,并将每个字符串写入文件作为一行。这对于需要一次性写入多行内容的场景非常有用。
1
2
3
|
lines_to_write = [ 'First line.\n' , 'Second line.\n' , 'Third line.\n' ] with open ( 'output.txt' , 'w' , encoding = 'utf-8' ) as file : file .writelines(lines_to_write) |
六、使用特定模块处理特定格式文件
- 处理CSV文件:使用Python的
csv
模块可以方便地读写CSV文件。通过创建csv.writer
对象来写入CSV文件,通过创建csv.reader
对象来读取CSV文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import csv # 写入CSV文件 with open ( 'data.csv' , 'w' , newline = ' ', encoding=' utf - 8 ') as file : writer = csv.writer( file ) writer.writerow([ 'Name' , 'Age' , 'City' ]) writer.writerows([[ 'Alice' , 30 , 'New York' ], [ 'Bob' , 25 , 'Los Angeles' ]]) # 读取CSV文件 with open ( 'data.csv' , 'r' , encoding = 'utf-8' ) as file : reader = csv.reader( file ) for row in reader: print (row) |
- 处理JSON文件:使用Python的
json
模块可以方便地进行JSON数据的序列化和反序列化。通过json.dump
方法将Python对象序列化为JSON格式并写入文件,通过json.load
方法从文件中反序列化JSON数据。
1
2
3
4
5
6
7
8
9
10
11
|
import json # 序列化对象并写入JSON文件 data = { 'name' : 'Alice' , 'age' : 30 , 'city' : 'New York' } with open ( 'data.json' , 'w' , encoding = 'utf-8' ) as file : json.dump(data, file , ensure_ascii = False , indent = 4 ) # 从JSON文件中反序列化对象 with open ( 'data.json' , 'r' , encoding = 'utf-8' ) as file : loaded_data = json.load( file ) print (loaded_data) |
以上这些方法涵盖了Python文件读写的常见场景,从基本的文件读取和写入到处理特定格式的文件,都提供了实用的解决方案。
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。
共有 0 条评论