1.文件txt讀寫標準用法
1.1寫入文件
要讀取文件,首先得使用?open()
?函數打開文件。
?
file = open(file_path, mode='r', encoding=None)
file_path
:文件的路徑,可以是絕對路徑或者相對路徑。mode
:文件打開模式,'r'
?代表以只讀模式打開文件,這是默認值,‘w’表示寫入模式。encoding
:文件的編碼格式,像?'utf-8'
、'gbk'
?等,默認值是?None
。
下面寫入文件的示例:
#寫入文件,當open(file_name,'w')時清除文件內容寫入新內容,當open(file_name,'a')時直接在文件結尾加入新內容
file_name = 'text.txt'
try:with open(file_name,'w',encoding='utf-8') as file:file.write("你好!我是老葉愛吃魚")file.write("\n你好呀,老葉,很高興認識你")
except Exception as e:print(f'出錯{e}')
系統會判斷時候會有text.txt文件,沒有的話會創建文件,加入寫入內容,示例ru
1.2讀取文件
下面是讀取文件示例:
#讀取文件
try:with open(file_name,'r',encoding='utf-8') as file:print(file.read())
except Exception as e:print(f'出錯時輸出{e}')
#打印出:你好!我是老葉愛吃魚 你好呀,老葉,很高興認識你
1.2.1?readline()
?方法
readline()
?方法每次讀取文件的一行內容,返回一個字符串。
# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 讀取第一行
line = file.readline()
while line:print(line.strip()) # strip() 方法用于去除行尾的換行符line = file.readline()
# 關閉文件
file.close()
1.2.2?readlines()
?方法
readlines()
?方法會讀取文件的所有行,并將每行內容作為一個元素存儲在列表中返回。
# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 讀取所有行
lines = file.readlines()
for line in lines:print(line.strip())
# 關閉文件
file.close()
1.2.3?迭代文件對象
可以直接對文件對象進行迭代,每次迭代會返回文件的一行內容。
# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 迭代文件對象
for line in file:print(line.strip())
# 關閉文件
file.close()
2. 二進制文件讀取
若要讀取二進制文件,需將?mode
?參數設置為?'rb'
。
# 以二進制只讀模式打開文件
with open('example.jpg', 'rb') as file:# 讀取文件全部內容content = file.read()# 可以對二進制數據進行處理,如保存到另一個文件with open('copy.jpg', 'wb') as copy_file:copy_file.write(content)
3. 大文件讀取
對于大文件,不建議使用?read()
?方法一次性讀取全部內容,因為這可能會導致內存不足。可以采用逐行讀取或者分塊讀取的方式。
3.1 逐行讀取
# 逐行讀取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:for line in file:# 處理每行內容print(line.strip())
3.2 分塊讀取
# 分塊讀取大文件
chunk_size = 1024 # 每次讀取 1024 字節
with open('large_file.txt', 'r', encoding='utf-8') as file:while True:chunk = file.read(chunk_size)if not chunk:break# 處理每個數據塊print(chunk)
4.Excel表格文件的讀寫
4.1讀取excel
import xlrd
import xlwt
from datetime import date,datetime# 打開文件
workbook = xlrd.open_workbook(r"D:\python_file\request_files\excelfile.xlsx", formatting_info=False)
# 獲取所有的sheet
print("所有的工作表:",workbook.sheet_names())
sheet1 = workbook.sheet_names()[0]# 根據sheet索引或者名稱獲取sheet內容
sheet1 = workbook.sheet_by_index(0)
sheet1 = workbook.sheet_by_name("Sheet1")# 打印出所有合并的單元格
print(sheet1.merged_cells)
for (row,row_range,col,col_range) in sheet1.merged_cells:print(sheet1.cell_value(row,col))# sheet1的名稱、行數、列數
print("工作表名稱:%s,行數:%d,列數:%d" % (sheet1.name, sheet1.nrows, sheet1.ncols))# 獲取整行和整列的值
row = sheet1.row_values(1)
col = sheet1.col_values(4)
print("第2行的值:%s" % row)
print("第5列的值:%s" % col)# 獲取單元格的內容
print("第一行第一列:%s" % sheet1.cell(0,0).value)
print("第一行第二列:%s" % sheet1.cell_value(0,1))
print("第一行第三列:%s" % sheet1.row(0)[2])# 獲取單元格內容的數據類型
# 類型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
print("第二行第三列的數據類型:%s" % sheet1.cell(3,2).ctype)# 判斷ctype類型是否等于data,如果等于,則用時間格式處理
if sheet1.cell(3,2).ctype == 3:data_value = xlrd.xldate_as_tuple(sheet1.cell_value(3, 2),workbook.datemode)print(data_value)print(date(*data_value[:3]))print(date(*data_value[:3]).strftime("%Y\%m\%d"))
4.2 設置單元格樣式
style = xlwt.XFStyle() # 初始化樣式
font = xlwt.Font() # 為樣式創建字體
font.name = name # 設置字體名字對應系統內字體
font.bold = bold # 是否加粗
font.color_index = 5 # 設置字體顏色
font.height = height # 設置字體大小# 設置邊框的大小
borders = xlwt.Borders()
borders.left = 6
borders.right = 6
borders.top = 6
borders.bottom = 6style.font = font # 為樣式設置字體
style.borders = bordersreturn style
4.3寫入excel
writeexcel = xlwt.Workbook() # 創建工作表
sheet1 = writeexcel.add_sheet(u"Sheet1", cell_overwrite_ok = True) # 創建sheetrow0 = ["編號", "姓名", "性別", "年齡", "生日", "學歷"]
num = [1, 2, 3, 4, 5, 6, 7, 8]
column0 = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"]
education = ["小學", "初中", "高中", "大學"]# 生成合并單元格
i,j = 1,0
while i < 2*len(education) and j < len(education):sheet1.write_merge(i, i+1, 5, 5, education[j], set_style("Arial", 200, True))i += 2j += 1# 生成第一行
for i in range(0, 6):sheet1.write(0, i, row0[i])# 生成前兩列
for i in range(1, 9):sheet1.write(i, 0, i)sheet1.write(i, 1, "a1")# 添加超鏈接
n = "HYPERLINK"
sheet1.write_merge(9,9,0,5,xlwt.Formula(n + '("https://www.baidu.com")'))# 保存文件
writeexcel.save("demo.xls")
5.cvs文件的讀寫操作
5.1讀取cvs文件
# 讀取 CSV 文件
def read_from_csv(file_path):try:with open(file_path, 'r', encoding='utf-8') as csvfile:reader = csv.reader(csvfile)print("讀取到的 CSV 文件內容如下:")for row in reader:print(row)except FileNotFoundError:print(f"錯誤: 文件 {file_path} 未找到!")except Exception as e:print(f"讀取文件時出錯: {e}")
5.2寫入cvs文件
# 寫入 CSV 文件
def write_to_csv(file_path, data):try:with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:writer = csv.writer(csvfile)# 寫入表頭writer.writerow(['Name', 'Age', 'City'])# 寫入數據行for row in data:writer.writerow(row)print(f"數據已成功寫入 {file_path}")except Exception as e:print(f"寫入文件時出錯: {e}")
6.SQL文件讀取
import sqlite3
import pandas as pd# 連接到SQLite數據庫
conn = sqlite3.connect('example.db')# 讀取數據庫表
query = "SELECT * FROM table_name"
data = pd.read_sql(query, conn)
print(data.head())# 關閉連接
conn.close()
7.cvs、xls、txt文件相互轉換
一般情況下python只會對cvs文件進行數據處理,那么對于很多文件屬于二進制文件不能直接處理,那么需要將二進制轉為cvs文件后才能處理,如xls是二進制文件需要對xls文件轉為cvs文件,操作數據后再轉成xls文件即可
7.1xls文件轉cvs文件
import pandas as pddef xls_to_csv(xls_file_path, csv_file_path):try:df = pd.read_excel(xls_file_path)df.to_csv(csv_file_path, index=False)print(f"成功將 {xls_file_path} 轉換為 {csv_file_path}")except Exception as e:print(f"轉換過程中出現錯誤: {e}")# 示例調用
xls_file = 'example.xls'
csv_file = 'example.csv'
xls_to_csv(xls_file, csv_file)
7.2cvs文件轉xls文件
import pandas as pddef csv_to_xls(csv_file_path, xls_file_path):try:df = pd.read_csv(csv_file_path)df.to_excel(xls_file_path, index=False)print(f"成功將 {csv_file_path} 轉換為 {xls_file_path}")except Exception as e:print(f"轉換過程中出現錯誤: {e}")# 示例調用
csv_file = 'example.csv'
xls_file = 'example.xls'
csv_to_xls(csv_file, xls_file)
7.3txt文件轉cvs文件
import pandas as pddef txt_to_csv(txt_file_path, csv_file_path):try:# 假設 txt 文件以空格分隔,根據實際情況修改 sep 參數df = pd.read_csv(txt_file_path, sep=' ', header=None)df.to_csv(csv_file_path, index=False, header=False)print(f"成功將 {txt_file_path} 轉換為 {csv_file_path}")except Exception as e:print(f"轉換過程中出現錯誤: {e}")# 示例調用
txt_file = 'example.txt'
csv_file = 'example.csv'
txt_to_csv(txt_file, csv_file)
7.4csv文件轉txt文件
import pandas as pddef csv_to_txt(csv_file_path, txt_file_path):try:df = pd.read_csv(csv_file_path)df.to_csv(txt_file_path, sep=' ', index=False, header=False)print(f"成功將 {csv_file_path} 轉換為 {txt_file_path}")except Exception as e:print(f"轉換過程中出現錯誤: {e}")# 示例調用
csv_file = 'example.csv'
txt_file = 'example.txt'
csv_to_txt(csv_file, txt_file)