python學習之檔案操作(一)

2021-09-29 11:54:35 字數 1858 閱讀 7148

一、檔案基本操作

參考資料:[1]

(一)**測試:

import os

print('test1', '\n')

print(os.listdir(os.getcwd()), '\n')

s = 'hello,world\n文字檔案讀寫方法\n文字檔案寫入方法'

with open('sample.txt', 'w') as fp:

print('# writable()測試檔案是否可寫:', fp.writable(), '\n')

fp.write(s)

print(os.listdir(os.getcwd()), '\n')

print('test2', '\n')

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

print('# seekable()是否支援隨機訪問:', fp.seekable())

print('# readable()當前檔案是否可讀:', fp.readable(), '\n')

print('# read()讀取檔案:', '\n', fp.read(), '\n')

print('# seek(offset, [,whence]) 其中whence=0是從檔案頭,1表示當前位置,2表示檔案尾:', fp.seek(3, 0))

print('# tell()返回檔案指標當前位置:', fp.tell(), '\n')

print('test1:', '\n')

fp = open('sample.txt', 'r+')

print('# truncate()擷取前size個位元組:', fp.truncate(5))

print('# read(3)讀取前三個字元:', fp.read(3), '\n')

print('當前檔案指標位置', fp.tell())

print('read()所讀取的內容:', fp.read())

print('seek(0, 0)設定檔案指標為檔案頭:', fp.seek(0, 0))

print('read()讀取的內容:', fp.read())

fp.close()

os.remove(os.getcwd() + '\\sample.txt') # 刪除sample檔案

(二) 測試結果

test1 

['.idea', 'filecontent.py']

# writable()測試檔案是否可寫: true

['.idea', 'filecontent.py', 'sample.txt']

test2

# seekable()是否支援隨機訪問: true

# readable()當前檔案是否可讀: true

# read()讀取檔案:

hello,world

文字檔案讀寫方法

文字檔案寫入方法

# seek(offset, [,whence]) 其中whence=0是從檔案頭,1表示當前位置,2表示檔案尾: 3

# tell()返回檔案指標當前位置: 3

test3:

# truncate()擷取前size個位元組: 5

# read(3)讀取前三個字元: hel

當前檔案指標位置 3

read()所讀取的內容: lo

seek(0, 0)設定檔案指標為檔案頭: 0

read()讀取的內容: hello

python學習之檔案操作

在python中,操作檔案和目錄的函式一部分放在os模組中,一部分放在os.path模組中。os.listdir 返回path指定的資料夾包含的檔案或資料夾的名字的列表 os.getcwd 返回當前工作目錄 os.chdir 改變當前工作目錄 os.mkdir 建立資料夾 os.makedirs 遞...

Python學習之檔案操作

檔案開啟方法 open name mode buf name 檔案路徑 mode 開啟方式 buf 緩衝buffering大小 此處以只寫方式開啟,如果檔案不存在其實就是建立了該檔案 檔案讀取方式 1 read size 讀取檔案 讀取size個位元組,預設全部讀取 2 readline size ...

Python學習筆記之檔案操作

在任何一門程式語言中,檔案的操作都是最基本的功能。python在檔案操作方面非常的簡單直接,內建了讀寫檔案的函式,在程式中直接呼叫即可。在讀寫檔案中,會有各種各樣的問題,比如檔案是否存在,是否有許可權,如何捕捉讀寫異常,這些在python中都很簡單。假設我們在專案目錄中已經有了test.txt檔案 ...