欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中各種常見文件的讀寫操作與類型轉(zhuǎn)換詳細(xì)指南

 更新時(shí)間:2025年04月20日 11:53:16   作者:老葉愛(ài)吃魚  
這篇文章主要為大家詳細(xì)介紹了python中各種常見文件(txt,xls,csv,sql,二進(jìn)制文件)的讀寫操作與類型轉(zhuǎn)換,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1.文件txt讀寫標(biāo)準(zhǔn)用法

1.1寫入文件

要讀取文件,首先得使用 open() 函數(shù)打開文件。

file = open(file_path, mode='r', encoding=None)

file_path:文件的路徑,可以是絕對(duì)路徑或者相對(duì)路徑。

mode:文件打開模式,'r' 代表以只讀模式打開文件,這是默認(rèn)值,‘w’表示寫入模式。

encoding:文件的編碼格式,像 'utf-8'、'gbk' 等,默認(rèn)值是 None。

下面寫入文件的示例:

#寫入文件,當(dāng)open(file_name,'w')時(shí)清除文件內(nèi)容寫入新內(nèi)容,當(dāng)open(file_name,'a')時(shí)直接在文件結(jié)尾加入新內(nèi)容
file_name = 'text.txt'
try:
    with open(file_name,'w',encoding='utf-8') as file:
        file.write("你好!我是老葉愛(ài)吃魚")
        file.write("\n你好呀,老葉,很高興認(rèn)識(shí)你")
except Exception as e:
    print(f'出錯(cuò){e}')

系統(tǒng)會(huì)判斷時(shí)候會(huì)有text.txt文件,沒(méi)有的話會(huì)創(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'出錯(cuò)時(shí)輸出{e}')
#打印出:你好!我是老葉愛(ài)吃魚     你好呀,老葉,很高興認(rèn)識(shí)你

1.2.1 readline() 方法

readline() 方法每次讀取文件的一行內(nèi)容,返回一個(gè)字符串。

# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 讀取第一行
line = file.readline()
while line:
    print(line.strip())  # strip() 方法用于去除行尾的換行符
    line = file.readline()
# 關(guān)閉文件
file.close()

1.2.2 readlines() 方法

readlines() 方法會(huì)讀取文件的所有行,并將每行內(nèi)容作為一個(gè)元素存儲(chǔ)在列表中返回。

# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 讀取所有行
lines = file.readlines()
for line in lines:
    print(line.strip())
# 關(guān)閉文件
file.close()

1.2.3 迭代文件對(duì)象

可以直接對(duì)文件對(duì)象進(jìn)行迭代,每次迭代會(huì)返回文件的一行內(nèi)容。

# 打開文件
file = open('example.txt', 'r', encoding='utf-8')
# 迭代文件對(duì)象
for line in file:
    print(line.strip())
# 關(guān)閉文件
file.close()

2. 二進(jìn)制文件讀取

若要讀取二進(jìn)制文件,需將 mode 參數(shù)設(shè)置為 'rb'。

# 以二進(jìn)制只讀模式打開文件
with open('example.jpg', 'rb') as file:
    # 讀取文件全部?jī)?nèi)容
    content = file.read()
    # 可以對(duì)二進(jìn)制數(shù)據(jù)進(jìn)行處理,如保存到另一個(gè)文件
    with open('copy.jpg', 'wb') as copy_file:
        copy_file.write(content)

3. 大文件讀取

對(duì)于大文件,不建議使用 read() 方法一次性讀取全部?jī)?nèi)容,因?yàn)檫@可能會(huì)導(dǎo)致內(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
        # 處理每個(gè)數(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,如果等于,則用時(shí)間格式處理
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 設(shè)置單元格樣式

style = xlwt.XFStyle()    # 初始化樣式
font = xlwt.Font()    # 為樣式創(chuàng)建字體
font.name = name    # 設(shè)置字體名字對(duì)應(yīng)系統(tǒng)內(nèi)字體
font.bold = bold    # 是否加粗
font.color_index = 5    # 設(shè)置字體顏色
font.height = height    # 設(shè)置字體大小
 
# 設(shè)置邊框的大小
borders = xlwt.Borders()
borders.left = 6
borders.right = 6
borders.top = 6
borders.bottom = 6
 
style.font = font    # 為樣式設(shè)置字體
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 = ["編號(hào)", "姓名", "性別", "年齡", "生日", "學(xué)歷"]
num = [1, 2, 3, 4, 5, 6, 7, 8]
column0 = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"]
education = ["小學(xué)", "初中", "高中", "大學(xué)"]
 
# 生成合并單元格
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"錯(cuò)誤: 文件 {file_path} 未找到!")
    except Exception as e:
        print(f"讀取文件時(shí)出錯(cuò): {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"寫入文件時(shí)出錯(cuò): {e}")

6.SQL文件讀取

import sqlite3
import pandas as pd
 
# 連接到SQLite數(shù)據(jù)庫(kù)
conn = sqlite3.connect('example.db')
 
# 讀取數(shù)據(jù)庫(kù)表
query = "SELECT * FROM table_name"
data = pd.read_sql(query, conn)
print(data.head())
 
# 關(guān)閉連接
conn.close()

7.cvs、xls、txt文件相互轉(zhuǎn)換

一般情況下python只會(huì)對(duì)cvs文件進(jìn)行數(shù)據(jù)處理,那么對(duì)于很多文件屬于二進(jìn)制文件不能直接處理,那么需要將二進(jìn)制轉(zhuǎn)為cvs文件后才能處理,如xls是二進(jìn)制文件需要對(duì)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)換過(guò)程中出現(xiàn)錯(cuò)誤: {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)換過(guò)程中出現(xiàn)錯(cuò)誤: {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:
        # 假設(shè) txt 文件以空格分隔,根據(jù)實(shí)際情況修改 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)換過(guò)程中出現(xiàn)錯(cuò)誤: {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)換過(guò)程中出現(xiàn)錯(cuò)誤: {e}")
 
# 示例調(diào)用
csv_file = 'example.csv'
txt_file = 'example.txt'
csv_to_txt(csv_file, txt_file)

以上就是python中各種常見文件的讀寫操作與類型轉(zhuǎn)換詳細(xì)指南的詳細(xì)內(nèi)容,更多關(guān)于python文件讀寫與類型轉(zhuǎn)換的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論