
如何使用Requests-OAuthlib實現OAuth認證
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 寫入文件
with open('example.txt', 'w') as file:
file.write('Hello, World!')
# 追加內容到文件
with open('example.txt', 'a') as file:
file.write('
New line')
# 讀取文件的某一行
with open('example.txt', 'r') as file:
line = file.readlines()[0]
print(line)
# 逐行讀取文件
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
fileinput
模塊修改文件內容import fileinput
# 使用fileinput模塊修改文件內容
for line in fileinput.input('example.txt', inplace=True):
print(line.replace('old_text', 'new_text'), end='')
# 復制文件
with open('example.txt', 'r') as source, open('copy.txt', 'w') as destination:
destination.write(source.read())
# 移動文件
import os
os.rename('example.txt', 'moved_example.txt')
# 刪除文件
import os
os.remove('example.txt')
# 重命名文件
import os
os.rename('example.txt', 'renamed_example.txt')
# 創建文件夾
import os
os.mkdir('new_folder')
# 刪除文件夾
import os
os.rmdir('new_folder')
# 遍歷文件夾中的所有文件
import os
for file in os.listdir('.'):
print(file)
# 獲取文件大小
import os
file_size = os.path.getsize('example.txt')
print(file_size)
# 檢查文件是否存在
import os
if os.path.exists('example.txt'):
print("文件存在")
else:
print("文件不存在")
# 讀取文件并去除空格
with open('example.txt', 'r') as file:
content = file.read().strip()
print(content)
# 讀取文件并按行分割
with open('example.txt', 'r') as file:
lines = file.read().splitlines()
print(lines)
# 讀取文件并統計行數
with open('example.txt', 'r') as file:
line_count = sum(1 for line in file)
print(line_count)
# 讀取文件并查找特定文本
with open('example.txt', 'r') as file:
if 'target_text' in file.read():
print("找到目標文本")
else:
print("未找到目標文本")
# 將文件內容轉換為列表
with open('example.txt', 'r') as file:
content_list = file.read().split()
print(content_list)
# 將文件內容轉換為字典
with open('example.txt', 'r') as file:
content_dict = dict(line.split() for line in file)
print(content_dict)
# 寫入多行內容到文件
with open('example.txt', 'w') as file:
file.write('Line 1
Line 2
Line 3')
pathlib
模塊復制文件# 使用pathlib模塊復制文件
from pathlib import Path
source = Path('example.txt')
destination = Path('copy.txt')
source.replace(destination)
pathlib
模塊移動文件# 使用pathlib模塊移動文件
from pathlib import Path
file = Path('example.txt')
file.rename('moved_example.txt')
pathlib
模塊創建和刪除文件夾# 使用pathlib模塊創建和刪除文件夾
from pathlib import Path
# 創建文件夾
new_folder = Path('new_folder')
new_folder.mkdir()
# 刪除文件夾
new_folder.rmdir()
本文這些案例可以幫助大家更高效地處理文本文件,提高大家的Python編程技能。
本文轉載自: Python處理文本的25個經典操作