Python之檔案讀取和寫入

2021-08-09 22:15:09 字數 1742 閱讀 8564

python之檔案管理

1.檔案讀取:

匯入模組:import codecs

開啟檔案例項:

#!/usr/bin/env python

# -*- coding:utf8 -*-

# @time     : 2017/10/27 9:57

# @author   : hantong

# @file     : file.py

import codecs

f = codecs.open('1.txt',encoding="utf-8") #建議字符集設定,不設定有時候會出現亂碼

txt1 = f.read()

print(txt1)

f.close()

這樣可以讀取檔案所有內容,如果想要按行讀取,則使用readline和readlines

# readline讀取一行即停止,游標處在檔案末尾,readlines則是逐行讀取所有內容,並且生成乙個list

**如下:

f = open('1.txt')

t1 = f.readline()

print(t1)

f.close()

結果只顯示檔案第一行

f = open('1.txt')

t2 = f.readlines()

print(t2)

f.close()

結果如下:

['11111\n', '222\n', 'ggg\n', 'eeerr\n', 'jjjj'] 生成了乙個列表

如果要讀取下一行,可以使用next,用法與readline一樣,不在詳說。

2.新建寫入檔案

寫入內容到檔案,使用write

**如下:

import codecs

f = codecs.open('2.txt','w')

f.write('hello world\n')

f.write('hello world one\n')

f.write('hello world two\n')

f.write('hello world three\n')

print(f)

f.close()

這樣就可以新建2.txt檔案,並寫入以上內容,**模式與read一樣

3.with的用法

細心的同學都會發現,上面**每次結尾都會使用f.close()關閉檔案,這樣會比較容易出現忘記寫這行語句的情況,這樣的話檔案其實一直是開啟狀態的,為了避免出現這樣的情況,那麼with就應運而生了。

**如下:

with open('2.txt') as f:

t2 = f.read()

print(t2)

這樣就可以操作2.txt這個檔案了.無需再寫f.close()關閉檔案,每次操作之後會自行關閉。

python 檔案讀取和寫入

def upload file request try if request.method post data request.files data assert data,引數必傳 data num random.randint 0,100 file name os.path.join setti...

python基礎之 csv檔案讀取和寫入

其檔案以純文字形式儲存 資料 數字和文字 一般以逗號分隔值 包含需要的csv支援方法等 最基本的操作,這時候我們檔案開啟後是要自己關閉的 filename open demo2.csv r encoding utf 8 filename.close 我們換成with as,就可以實現自動關閉 結束w...

python 檔案的讀取和寫入

檔案讀取 with open 當前目錄檔名或指定目錄檔案 as file object contents file object.read 讀取檔案返回整個檔案 lines file object.readlines 讀取檔案返回檔案行列表 for line in lines print line....