原文来自:blog.csdn.net/liukang325/article/details/46724365
今天学习到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
#!/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 要踏踏实实的学 :)