python编程快速上手——读写文件

  • Post author:
  • Post category:python


基本操作:

1.windows上的反斜杠与linux即OSX上的正斜杠

这里介绍一个os.path.join()函数,它可以返回一个文件路径名称的字符串,包括正确的路径分隔符。

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
​

>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
         print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx


​

2.修改当前工作目录

可以利用os.getcwd()函数,可以取得当前工作路径的字符串,并利用oschdir()改变它。

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'

3.相对路径与绝对路径

绝对路径它总是从根文件夹开始,相对路径它相对于程序当前的工作目录,eg:

4.使用

os.makedirs()创建新文件夹

>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')

os.path模块是比较重要的模块,详细信息可以在

http://docs.python.org/3/library/os.path.html找到。


5.处理相对路径以及绝对路径


调用os.path.abspath(path)将返回参数的绝对路径的字符串,这是将相对路径转为绝对路径的简便方法。


调用os.path.isabs(path),如果参数是绝对路径返回True,如果是相对路径返回False。

调用

os.path.relpath(path, start)将返回从start路径到path的相对路径的字符串,如果没有提供start,就使用当前工作目录作为开始路径。

>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
>>> os.path.relpath('C:\\Windows', 'C:\\')
'Windows'
>>> os.path.relpath('C:\\Windows', 'C:\\spam\\eggs')
'..\\..\\Windows'
>>> os.getcwd()
'C:\\Python34'

调用

os.path.dirname(path)


将返回一个字符串,它包含path参数中最后一个斜杠之前的所有内容。


调用os.path.basename(path)将返回一个字符串,


它包含 path 参数


中最后一个斜杠之后的所有内容。

>>> path = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.basename(path)
'calc.exe'
>>> os.path.dirname(path)
'C:\\Windows\\System32'

调用

os.path.split(),可获得一个路径的目录名称与基本名称,获得这两个字符串的元组。

>>> calcFilePath = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.split(calcFilePath)
('C:\\Windows\\System32', 'calc.exe')

也可以同时调用dirname与basename,有

>>> (os.path.dirname(calcFilePath), os.path.basename(calcFilePath))
('C:\\Windows\\System32', 'calc.exe')

os.path.split()


不会接受一个文件路径并返回每个文件夹的字符串的列表。如果需要这样,须使用


split()


字符串方法,并根据


os.path.sep


中的字符串进行分


割。

>>> calcFilePath.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe']

6.查看文件大小以及文件夹内容


调用


os.path.getsize(path)


将返回


path


参数中文件的字节数

调用os.listdir(path)


将返回文件名字符串的列表
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
776192
>>> os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']

如果想知道所有文件的总字节数,可以同时使用

os.path.getsize()





os.listdir()

>>> totalSize = 0
>>> for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
>>> print(totalSize)
1117846456

7.检查路径的有效性


如果


path


参数所指的文件或文件夹存在,调用


os.path.exists(path)


将返回


True




否则返回


False




如果


path


参数存在,并且是一个文件,调用


os.path.isfile(path)


将返回


True


,否

则返回


False




如果


path


参数存在,并且是一个文件夹,调用


os.path.isdir(path)


将返回


True




否则返回


False



>>> os.path.exists('C:\\Windows')
True
>>> os.path.exists('C:\\some_made_up_folder')
False
>>> os.path.isdir('C:\\Windows\\System32')
True
>>> os.path.isfile('C:\\Windows\\System32')
False
>>> os.path.isdir('C:\\Windows\\System32\\calc.exe')
False
>>> os.path.isfile('C:\\Windows\\System32\\calc.exe')
True

8.文件读写


调用


open()


函数,返回一个


File


对象。

#首先创建一个txt文件
>>> helloFile = open('C:\\Users\\your_home_folder\\hello.txt','r')


2


.调用


File


对象的


read()





write()


方法。

如果你希望将整个文件的


内容读取为一个字符串值,就使用


File


对象的


read()


方法.
>>> helloContent = helloFile.read()
>>> helloContent
'Hello world!'

如果想取得字符串列表,就使用readlines()方法

#创建一个txt文件
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate

#再进行操作
>>> sonnetFile = open('sonnet29.txt')
>>> sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my
outcast state,\n', And trouble deaf heaven with my bootless cries,\n', And
look upon myself and curse my fate,']
>>> baconFile = open('bacon.txt', 'w')
>>> baconFile.write('Hello world!\n')
13
>>> baconFile.close()
>>> baconFile = open('bacon.txt', 'a')
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
Hello world!
Bacon is not a vegetable.

9.用shelve模块保存变量


利用


shelve


模块,可以将


Python


程序中的变量保存到二进制的


shelf


文件中。
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats
>>> shelfFile.close()
>>> shelfFile = shelve.open('mydata')
>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
>>> shelfFile['cats']
['Zophie', 'Pooka', 'Simon']
>>> shelfFile.close()

shlef值也有keys()方法和values()方法

>>> shelfFile = shelve.open('mydata')
>>> list(shelfFile.keys())
['cats']
>>> list(shelfFile.values())
[['Zophie', 'Pooka', 'Simon']]
>>> shelfFile.close()

10.用

pprint.pformat()函数保存变量


pprint.pformat()


函数将提供一个字符串,可以将它写入


.py


文件。该文件将成为自己的模块,如果需要使用存储在其中的变量,就可以导入它。

import


语句导入的模块本身就是


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')
83
>>> 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'



版权声明:本文为ZBDX2113原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。