python 檔案讀寫異常 已解

2021-08-03 15:31:48 字數 2269 閱讀 4365

今天學習到python 關於txt 讀寫問題,親測發現乙個問題一直無解,先記錄下來慢慢啃

這個是檔案結構

1, 建立乙個包 :filepackage

a,裡面包含乙個 _ _ init _ _.py

b,乙個file.py

c,和乙個test.txt 測試檔案

2,建立和包 filepackage 同級別目錄下 test.py檔案,作為測試包的讀寫檔案

file.py code 如下:

#!/usr/bin/python

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

from datetime import datetime

class myfile():

def __init__(self, filepath):

print('myfile init...')

self.filepath = filepath

def printfilepath(self):

print(self.filepath)

def testreadfile(self):

with open(self.filepath, 'r') as f:

s = f.read()

print('open for read...')

print(s)

print "closed after read: ", f.closed

def testwritefile(self):

with open('test.txt', 'w') as f:

f.write('今天是 ')

f.write(datetime.now().strftime('%y-%m-%d'))

print "closed after write: ", f.closed

_ _ init_ _ code 如下

from file import myfile
test.txt 當中隨便寫些資料,以便於區別

abcd
然後,test.py code如下

#!/usr/bin/python

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

from file import myfile

if __name__ == '__main__':

a = myfile("./test.txt")

a.printfilepath();

a.testreadfile();

a.testwritefile();

但是,實際執行效果如下圖示,讀資料是對的,寫資料呢,完全沒有變化,而且不報錯,單雙引號之類的都嘗試過,還有f.closed()都試過,均無解

於是乎,先看下圖

我將 test.py檔案搬到子目錄,我想這樣能繞過_ _ init_ _,實際情況與預期相符,看圖

這是幾個意思呢,是不是_ _ init_ _寫的不對呢,先把問題記錄下來,請高手支招

今天是 2017-9-20

原來是我把相對路徑寫錯了,改了之後就可以正常讀寫了(詳見紅色高亮部分),code 如下

#!/usr/bin/python

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

from filepackage import myfile

if __name__ == '__main__':

a = myfile("./filepackage/test.txt")

a.printfilepath();

a.testreadfile();

a.testwritefile();

python 要踏踏實實的學 :)

python檔案讀寫,異常簡介

直接讀取 with在不需要訪問時自動關閉 開啟專案下的檔案,直接讀取 若要讀取指定檔案,則要輸入指定路徑 f pycharm project readwrite pi digits.txt with open pi digits.txt as file object contents file ob...

python檔案讀寫和異常

1,文字檔案 2,二進位制檔案 print type data with open 吉多.jpg wb as fs2 fs2.write data except filenotfounderror as e print 指定的檔案無法開啟.except ioerror as e print 讀寫檔案...

python檔案讀寫 異常處理

函式open 檔案讀寫,預設讀模式 open 路徑檔名.字尾名 eg file open d tes.txt content file.read print content file.close 讀 read 從文件開始位置讀取 readline 讀取一行內容,檔案指標在 就從 開始讀取一行 rea...