python操作文件

OS模块

1.getcwd()

用来获取当前工作目录

>>> import os
>>> os.getcwd()
'D:\\Postgraduate\\Python\\python数据分析\\python玩转数据'

2.chdir(path)

用来改变当前工作目录

>>> diri = 'D:/Postgraduate/Python/python数据分析/python玩转数据'
>>> os.chdir(diri)
>>> os.getcwd()
'D:\\Postgraduate\\Python\\python数据分析\\python玩转数据'

3.listdir(path='.')

用来列举当前目录下有哪些文件和子目录,默认值是'.',也可以用'..'代表上层目录

>>> os.listdir('.')
['0.txt', '1.txt', 'hash.py', 'python基础1', 'python基础2', 'test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'uwm-workshop', 'uwm-workshop.zip', '__pycache__', '强大的数据结构和python扩展库', '数据统计和可视化第五周', '数据统计和可视化第六周', '数据获取与表示', '文本相似度', '面向对象和图像用户界面', '项目实践']
>>> os.listdir('..')
['python玩转数据', '嵩老师数据分析MOOC']
>>> os.listdir(diri)
['0.txt', '1.txt', 'hash.py', 'python基础1', 'python基础2', 'test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'uwm-workshop', 'uwm-workshop.zip', '__pycache__', '强大的数据结构和python扩展库', '数据统计和可视化第五周', '数据统计和可视化第六周', '数据获取与表示', '文本相似度', '面向对象和图像用户界面', '项目实践']

os.path模块

介绍常用的os.path.join(path1[,path2[,...]]),将路径名和文件名组合成一个完整的路径

>>> diri = 'D:/Postgraduate/Python/python数据分析/python玩转数据'
>>> newf = os.path.join(diri,'test_1.txt')
>>> with open(newf,'r') as f:
    f.read()

    
'In many applications it is useful to record not only the fingerprints of a document,but also the position of the fingerprints in the document. For example, we needpositional information to show the matching substrings in a user interface. An efficient implementation of winnowing also needs to retain the position of the most recently selected fingerprint. Figure 2(f) shows the set of [fingerprint, position] pairs for this example (the first position is numbered 0). To avoid the notational complexity of indexing all hashes with their position in the global sequence of hashes of k-grams of a document, we suppress most explicit references to the position of k-grams in documents in our presentation.'

注意:文件打开以后记得关闭!

 

posted @ 2018-01-27 10:24  嶙羽  阅读(274)  评论(0编辑  收藏  举报