Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python读写文件

作者:灭世杀   发布日期:2025-02-19   浏览:101

# Python读写文件示例代码

# 1. 读取文件内容
# 使用with语句可以确保文件在使用完毕后被正确关闭
with open('example.txt', 'r') as file:
    content = file.read()  # 读取整个文件内容为字符串
    print(content)

# 2. 按行读取文件内容
with open('example.txt', 'r') as file:
    lines = file.readlines()  # 读取文件每一行,返回一个列表,每个元素是一行内容
    for line in lines:
        print(line.strip())  # 去除每行末尾的换行符

# 3. 写入文件内容
# 如果文件不存在则创建文件,如果文件存在则覆盖文件内容
with open('output.txt', 'w') as file:
    file.write("Hello, World!\n")  # 写入一行文本,加换行符
    file.write("This is another line.\n")

# 4. 追加内容到文件
# 如果文件不存在则创建文件,如果文件存在则在文件末尾追加内容
with open('output.txt', 'a') as file:
    file.write("This is an appended line.\n")

解释说明:

  • open() 函数用于打开文件,第一个参数是文件路径,第二个参数是模式('r' 表示只读,'w' 表示写入,'a' 表示追加)。
  • with 语句确保文件在使用完毕后自动关闭,避免资源泄露。
  • read() 方法读取整个文件内容为字符串。
  • readlines() 方法按行读取文件内容,返回一个包含各行内容的列表。
  • write() 方法写入字符串到文件中,'w' 模式会覆盖原有内容,'a' 模式会在文件末尾追加内容。

上一篇:python中pop

下一篇:python os模块

大家都在看

python时间格式

python ord和chr

python中的yield

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站