文件有2个关键属性:“文件名”和“路径”
1. 文件目录
在Windows上目录的分隔符是倒斜杠(\),在linux上的目录分隔符是正斜杠(/)
我们可以通过os.path.join()来获取目录
import os
os.path.join('use','bin', 'spam')
'usr//bin//spam'
os.getcwd() 当前工作目录
import os
os.getcwd()
os.chdir('c:\\windows\\system32')
os.getcwd()
os.makedirs()创建新文件夹
import os
os.makedirs('c:\\delicious\\walnut')
os.path.abspath(path) 获取绝对路径
os.path.abspath(.) # 获取相对路径.的绝对路径
os.path.abspath(‘。\\script’)
os.path.isabs('.') # 判断是否是绝对路径
os.path.dirname(path)返回最后一个分隔符前的所有内容
os.path.dirname(.)
os.path.basename(path)返回第一个分隔符前的所有内容
os.path.basename(.)
os.path.split(path) 获取路径和文件
os.path.split('c:\\windows\\aa.exe')
('c:\\window', 'aa.exe')
.split(os.path.sep)获取目录的每一个文件夹
calcFilePath = 'c:\\windows\\aa.exe'
calcFilePath.split(os.path.sep)
['c:', 'windows', 'aa.exe']
2. 文件大小
os.path.getsize(path)获取path文件的字节数
os.path.getsize('C:\\Windows\\System32\\calc.exe')
776192
os.listdir(path)获取文件名称
os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll']
3. 检查路径的有效性
os.path.exists(‘C:\Windows’) 文件或目录是否存在,存在true
os.path.exists('C:\\Windows')
True
os.path.isdir(‘C:\Windows\System32’)是否是目录
os.path.isdir('C:\\Windows\\System32')
True
os.path.isfile(‘C:\Windows\System32’)是否是文件
os.path.isfile('C:\\Windows\\System32')
False
4. 文件读写
- 调用open(), 返回File对象
- 调用File的read()或write()
- 调用File的close()方法
helloFile = open('C:\\Users\\your_home_folder\\hello.txt')
helloContent = helloFile.read() # sonnetFile.readlines()
>>>baconFile = open('bacon.txt', 'w') # 写覆盖
>>> baconFile.write('Hello world!\n')
>>> baconFile.close()
>>> baconFile = open('bacon.txt', 'a') # 写追加
>>> baconFile.write('Bacon is not a vegetable.')
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
Hello world!Bacon is not a vegetable.
4.1 shelve模块保存变量
利用shelve模块,你可以将Python程序中的变量保存到二进制的shelf文件中。这样,程序就可以从硬盘中恢复变量的数据。shelve模块让你在程序中添加“保存”和“打开”功能。例如,如果运行一个程序,并输入了一些配置设置,就可以将这些设置保存到一个shelf文件,然后让程序下一次运行时加载它们
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats
>>> shelfFile.close()
在Windows上运行前面的代码,你会看到在当前工作目录下有3个新文件:mydata.bak、mydata.dat和mydata.dir,OS X上,只会创建一个mydata.db文件.
shelfFile = shelve.open('mydata')
>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
>>> shelfFile['cats']
['Zophie', 'Pooka', 'Simon']
>>> shelfFile.close()
4.2 用pprint.pformat()函数保存变量
pprint.pformat()函数将返回同样的文本字符串,但不是打印它。这个字符串不仅是易于阅读的格式,同时也是语法上正确的Python代码。假定你有一个字典,保存在一个变量中,你希望保存这个变量和它的内容,以便将来使用。pprint.pformat()函数将提供一个字符串,你可以将它写入.py文件。该文件将成为你自己的模块,如果你需要使用存储在其中的变量,就可以导入它
import pprint
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
>>> fileObj.close()
>>>import myCats
>>> myCats.cats
[{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> myCats.cats[0]
{'name': 'Zophie', 'desc': 'chubby'}
>>> myCats.cats[0]['name']'Zophie'