专业编程基础技术教程

网站首页 > 基础教程 正文

一文掌握Python找到文件操作(python在文件中查找指定数据)

ccvgpt 2025-03-19 10:59:19 基础教程 3 ℃

阅读文件

读取文件的全部内容:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

2. 写入文件

将文本写入文件,覆盖现有内容:

一文掌握Python找到文件操作(python在文件中查找指定数据)

with open('example.txt', 'w') as file:
    file.write('Hello, Python!')

3. 向文件追加

将文本添加到现有文件末尾:

with open('example.txt', 'a') as file:
    file.write('\nAppend this line.')

4. 将行读取到列表中

读取文件并将每一行添加到列表中:

with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)

5. 遍历文件中的每一行

处理文件中的每一行:

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

6. 检查文件是否存在

在执行文件操作之前检查文件是否存在:

import os
if os.path.exists('example.txt'):
    print('File exists.')
else:
    print('File does not exist.')

7. 将列表写入文件

将列表中的每个元素写入文件的新行:

lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
    for line in lines:
        file.write(f'{line}\n')

8. 使用 With 块处理多个文件

同时使用with块处理多个文件:

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
    content = source.read()
    destination.write(content)

9. 删除文件

安全删除文件(如果存在):

import os
if os.path.exists('example.txt'):
    os.remove('example.txt')
    print('File deleted.')
else:
    print('File does not exist.')

10. 读取和写入二进制文件

从文件以二进制模式读取和写入(适用于图像、视频等):

# Reading a binary file
with open('image.jpg', 'rb') as file:
    content = file.read()
# Writing to a binary file
with open('copy.jpg', 'wb') as file:
    file.write(content)

最近发表
标签列表