詳解Python的檔案處理

2022-09-21 16:48:09 字數 2357 閱讀 3437

目錄

比如像以前在學校讀書的時候,第一門程式設計課設計要求是製作學生管理系統。

這就需要使用檔案來處理(也可以用資料庫,但是一般c語言都是很多計算機系新生的首選語言,這時候大概率也不知道資料庫)。

ycnjgrckgpython 最常用的是open和write函式,如下:

#open函式:接收乙個檔名,還有其他引數可省略不寫。

one_file = open('myfile.txt')

#讀取資料賦值給data變數

data = one_file.read()

#乙個檔案物件的write函式

one_file = open('myfile.txt','w')

#write函式:傳入資料,write函式把資料寫入到one_file對應的檔案中。

one_file.write('寫到檔案的資料')

程式設計客棧

保留下面資料到為檔案:sample.txt

持續學習

持續開發

我雷學委

afile = open("sample.txt")

print(afile.read())

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @time : 2021/11/12 11:58 下午

# @author : leixuewei

# @csdn/juejin/wechat: 雷學委

# @xueweitag: codingdemo

# @file : filedemo.py

# @project : hello

afile = open("sample.txt")

data = afile.read()

print("sample file content=", data)

afile.close()

#把sample讀取的資料寫到test檔案

afile = open("./test.txt", "w")

afile.write(data)

afile.close()

print("write data to test file!")

afile = open("./test.txt")

data = afile.read()

afile.close()

print("test file content=", data)

我們看,讀取到的內容確實是寫入的。

這個檔案操作非常簡單。

讀寫檔案就這麼簡單,但是我們操作檔案之後,記得呼叫close函式(關閉檔案,不然後續再讀寫操作會出現異常/錯誤!)

close函式的呼叫如下:

one_file.close() #檔案物件.close()

但是我們通常都是編寫這種風格的檔案讀寫:

with open('sample.txt', 'r') as one_file:

data = one_file.read()

#無須呼叫close了,這個with**塊內,python會幫我們自動關閉檔案。

以上都是一開檔案就一次性讀取的,python中還可以一行一行讀取。

我們基於前面讀寫檔案**改造,直接看:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @time : 2021/11/12 11:58 下午

# @author : leixuewei

# @csdn/juejin/wechat: 雷學委

# @xueweitag:

# @file : filedemo2.py

# @project : hello

with open("sample.txt") as afile:

data = afile.readline()

print("sample filycnjgrckge content=", data)

with open("./test.txt", "w") as afile:

afile.write(data)

print("write data to test file!")

with open("test.txt") as afile:

data = afile.readline()

print("test file content=", data)

我們看到這裡讀取了sample檔案的一行,然後寫入到test檔案,也只有一行!

python 檔案的讀取非常方便,內建的open函式和檔案物件自www.cppcns.com帶的write函式,設計非常簡單。

本文標題: 詳解python的檔案處理

本文位址:

Python學習之檔案處理詳解

本文和大家分享的主要是python 學習python有所幫助。檔案處理 開啟檔案時,需要指定檔案路徑和以何等方式開啟檔案,開啟後,可以將結果賦值給乙個變數,這個變數我們稱為控制代碼。這樣我們就可以通過這個控制代碼對此檔案進行操作。使用後關閉。f open 檔案路徑 開啟方式 encoding 字元編...

詳解python檔案的操作和異常的處理

目錄 格式 f open 檔案 w 或者f open 檔案 r 格式 f open 檔案 w 或者f open 檔案 r 物件 open 檔案 r 變數 物件.read print 變數 如果用open開啟檔案時,如果使用的 r 那麼可以省略,即只寫 open test.txt 如果沒有檔案,開啟報...

python的檔案處理

f open f.txt w r唯讀,w可寫,a追加 for i in range 0,10 f.write str i n f.close open是python的內建函式,有時候檔案由於編碼的不同,會造成亂碼,為了解決這個問題 可以使用codecs模組來解決這個問題 import codecs ...