python中各種常見文件的讀寫操作與類型轉(zhuǎn)換詳細指南
1.文件txt讀寫標準用法
1.1寫入文件
要讀取文件,首先得使用 open() 函數(shù)打開文件。
file = open(file_path, mode='r', encoding=None)
file_path:文件的路徑,可以是絕對路徑或者相對路徑。
mode:文件打開模式,'r' 代表以只讀模式打開文件,這是默認值,‘w’表示寫入模式。
encoding:文件的編碼格式,像 'utf-8'、'gbk' 等,默認值是 None。
下面寫入文件的示例:
#寫入文件,當open(file_name,'w')時清除文件內(nèi)容寫入新內(nèi)容,當open(file_name,'a')時直接在文件結(jié)尾加入新內(nèi)容
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}')
系統(tǒng)會判斷時候會有text.txt文件,沒有的話會創(chuàng)建文件,加入寫入內(nèi)容,示例如下

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() 方法每次讀取文件的一行內(nèi)容,返回一個字符串。
# 打開文件
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() 方法會讀取文件的所有行,并將每行內(nèi)容作為一個元素存儲在列表中返回。
# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 讀取所有行
lines = file.readlines()
for line in lines:
print(line.strip())
# 關閉文件
file.close()
1.2.3 迭代文件對象
可以直接對文件對象進行迭代,每次迭代會返回文件的一行內(nèi)容。
# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 迭代文件對象
for line in file:
print(line.strip())
# 關閉文件
file.close()
2. 二進制文件讀取
若要讀取二進制文件,需將 mode 參數(shù)設置為 'rb'。
# 以二進制只讀模式打開文件
with open('example.jpg', 'rb') as file:
# 讀取文件全部內(nèi)容
content = file.read()
# 可以對二進制數(shù)據(jù)進行處理,如保存到另一個文件
with open('copy.jpg', 'wb') as copy_file:
copy_file.write(content)
3. 大文件讀取
對于大文件,不建議使用 read() 方法一次性讀取全部內(nèi)容,因為這可能會導致內(nèi)存不足??梢圆捎弥鹦凶x取或者分塊讀取的方式。
3.1 逐行讀取
# 逐行讀取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
# 處理每行內(nèi)容
print(line.strip())
3.2 分塊讀取
# 分塊讀取大文件
chunk_size = 1024 # 每次讀取 1024 字節(jié)
with open('large_file.txt', 'r', encoding='utf-8') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
# 處理每個數(shù)據(jù)塊
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]
# 根據(jù)sheet索引或者名稱獲取sheet內(nèi)容
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的名稱、行數(shù)、列數(shù)
print("工作表名稱:%s,行數(shù):%d,列數(shù):%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)
# 獲取單元格的內(nèi)容
print("第一行第一列:%s" % sheet1.cell(0,0).value)
print("第一行第二列:%s" % sheet1.cell_value(0,1))
print("第一行第三列:%s" % sheet1.row(0)[2])
# 獲取單元格內(nèi)容的數(shù)據(jù)類型
# 類型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
print("第二行第三列的數(shù)據(jù)類型:%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() # 為樣式創(chuàng)建字體 font.name = name # 設置字體名字對應系統(tǒng)內(nèi)字體 font.bold = bold # 是否加粗 font.color_index = 5 # 設置字體顏色 font.height = height # 設置字體大小 # 設置邊框的大小 borders = xlwt.Borders() borders.left = 6 borders.right = 6 borders.top = 6 borders.bottom = 6 style.font = font # 為樣式設置字體 style.borders = borders return style
4.3寫入excel
writeexcel = xlwt.Workbook() # 創(chuàng)建工作表
sheet1 = writeexcel.add_sheet(u"Sheet1", cell_overwrite_ok = True) # 創(chuàng)建sheet
row0 = ["編號", "姓名", "性別", "年齡", "生日", "學歷"]
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 += 2
j += 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 文件內(nèi)容如下:")
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'])
# 寫入數(shù)據(jù)行
for row in data:
writer.writerow(row)
print(f"數(shù)據(jù)已成功寫入 {file_path}")
except Exception as e:
print(f"寫入文件時出錯: {e}")
6.SQL文件讀取
import sqlite3
import pandas as pd
# 連接到SQLite數(shù)據(jù)庫
conn = sqlite3.connect('example.db')
# 讀取數(shù)據(jù)庫表
query = "SELECT * FROM table_name"
data = pd.read_sql(query, conn)
print(data.head())
# 關閉連接
conn.close()
7.cvs、xls、txt文件相互轉(zhuǎn)換
一般情況下python只會對cvs文件進行數(shù)據(jù)處理,那么對于很多文件屬于二進制文件不能直接處理,那么需要將二進制轉(zhuǎn)為cvs文件后才能處理,如xls是二進制文件需要對xls文件轉(zhuǎn)為cvs文件,操作數(shù)據(jù)后再轉(zhuǎn)成xls文件即可
7.1xls文件轉(zhuǎn)cvs文件
import pandas as pd
def 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} 轉(zhuǎn)換為 {csv_file_path}")
except Exception as e:
print(f"轉(zhuǎn)換過程中出現(xiàn)錯誤: {e}")
# 示例調(diào)用
xls_file = 'example.xls'
csv_file = 'example.csv'
xls_to_csv(xls_file, csv_file)
7.2cvs文件轉(zhuǎn)xls文件
import pandas as pd
def 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} 轉(zhuǎn)換為 {xls_file_path}")
except Exception as e:
print(f"轉(zhuǎn)換過程中出現(xiàn)錯誤: {e}")
# 示例調(diào)用
csv_file = 'example.csv'
xls_file = 'example.xls'
csv_to_xls(csv_file, xls_file)
7.3txt文件轉(zhuǎn)cvs文件
import pandas as pd
def txt_to_csv(txt_file_path, csv_file_path):
try:
# 假設 txt 文件以空格分隔,根據(jù)實際情況修改 sep 參數(shù)
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} 轉(zhuǎn)換為 {csv_file_path}")
except Exception as e:
print(f"轉(zhuǎn)換過程中出現(xiàn)錯誤: {e}")
# 示例調(diào)用
txt_file = 'example.txt'
csv_file = 'example.csv'
txt_to_csv(txt_file, csv_file)
7.4csv文件轉(zhuǎn)txt文件
import pandas as pd
def 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} 轉(zhuǎn)換為 {txt_file_path}")
except Exception as e:
print(f"轉(zhuǎn)換過程中出現(xiàn)錯誤: {e}")
# 示例調(diào)用
csv_file = 'example.csv'
txt_file = 'example.txt'
csv_to_txt(csv_file, txt_file)
以上就是python中各種常見文件的讀寫操作與類型轉(zhuǎn)換詳細指南的詳細內(nèi)容,更多關于python文件讀寫與類型轉(zhuǎn)換的資料請關注腳本之家其它相關文章!
相關文章
pandas將Series轉(zhuǎn)成DataFrame的實現(xiàn)
本文主要介紹了pandas將Series轉(zhuǎn)成DataFrame的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01
python實現(xiàn)將一個數(shù)組逆序輸出的方法
今天小編就為大家分享一篇python實現(xiàn)將一個數(shù)組逆序輸出的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python通過自定義isnumber函數(shù)判斷字符串是否為數(shù)字的方法
這篇文章主要介紹了python通過自定義isnumber函數(shù)判斷字符串是否為數(shù)字的方法,涉及Python操作字符串判斷的相關技巧,需要的朋友可以參考下2015-04-04
Python實現(xiàn)解析與生成JSON數(shù)據(jù)
JSON文件是一種輕量級的數(shù)據(jù)交換格式,它采用了一種類似于JavaScript語法的結(jié)構(gòu),可以方便地在不同平臺和編程語言之間進行數(shù)據(jù)交換,下面我們就來學習一下Python如何使用內(nèi)置的json模塊來讀取和寫入JSON文件吧2023-12-12
Python實現(xiàn)SqlServer查詢結(jié)果并寫入多個Sheet頁的方法詳解
這篇文章主要為大家整理了兩個Python實現(xiàn)SqlServer查詢結(jié)果并寫入多個Sheet頁的方法,文中的示例代碼講解詳細,感興趣的可以了解一下2022-12-12

