Python编程快速上手8章读写文件

os.path.join()函数
如果需要创建文件名称的字符串,os.path.join()函数就很有用。
Windows—‘usr\bin\spam’
Linux—‘usr/bin/spam’
当前工作目录
os.getcwd()函数
os.chdir()改变它
绝对路径与相对路径
• “绝对路径”,总是从根文件夹开始。
• “相对路径”,它相对于程序的当前工作目录。
os.makedirs()创建新文件夹
创建所有必要的中间文件夹,目的是确保完整路径名存在。
处理绝对路径和相对路径
• 调用 os.path.abspath(path)将返回参数的绝对路径的字符串。这是将相对路径转
换为绝对路径的简便方法。
• 调用 os.path.isabs(path),如果参数是一个绝对路径,就返回 True,如果参数是
一个相对路径,就返回 False。
• 调用 os.path.relpath(path, start)将返回从 start 路径到 path 的相对路径的字符串。
如果没有提供 start,就使用当前工作目录作为开始路径。
调用 os.path.dirname(path)将返回一个字符串,它包含 path 参数中最后一个斜杠
之前的所有内容。
调用 os.path.basename(path)将返回一个字符串,它包含 path 参数中最后一个斜杠之后的所有内容。

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

如果同时需要一个路径的目录名称和基本名称,就可以调用 os.path.split(),获得这两个字符串的元组:
os.path.split()不会接受一个文件路径并返回每个文件夹的字符串的列表。如果需要这样,请使用split()字符串方法,
并根据os.path.sep 中的字符串进行分割。

>>> calcFilePath.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe']
#在 OS X 和 Linux 系统上,返回的列表头上有一个空字符串:
>>> '/usr/bin'.split(os.path.sep)
['', 'usr', 'bin']

查看文件大小和文件夹内容
• 调用 os.path.getsize(path)将返回 path 参数中文件的字节数。
• 调用 os.listdir(path)将返回文件名字符串的列表,包含 path 参数中的每个文件
检查路径有效性

>>> 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

文件读写过程
在 Python 中,读写文件有 3 个步骤:
1.调用 open()函数,返回一个 File 对象。
2.调用 File 对象的 read()或 write()方法。
3.调用 File 对象的 close()方法,关闭该文件。

>>> 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.

用 shelve 模块保存变量
利用 shelve 模块,你可以将 Python 程序中的变量保存到二进制的 shelf 文件中。
这样,程序就可以从硬盘中恢复变量的数据。
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()

就像字典一样,shelf 值有 keys()和 values()方法,返回 shelf 中键和值的类似列表的值。
要变成list就要用list方法。

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

用 pprint.pformat()函数保存变量

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

项目:生成随机的测验试卷文件

import random,os,shutil
shutil.rmtree('tests')
try:
    os.makedirs('tests\\answers')
except:
    print('file is already exits.')
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New\
Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West\
Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
for test in range(35):
    testFile = open('tests\\NO_%sTest.txt' % (test),'w')
    answerFile = open('tests\\answers\\NO_%sAnswer.txt' % (test),'w')
    testFile.write('NO_%s test.\nname:\nclass:\n')
    allQuestion = list(capitals.keys())
    random.shuffle(allQuestion)
    for questionNum in range(50):
        rightAnswer = capitals[allQuestion[questionNum]]
        errorAnswer = list(capitals.values())
        del errorAnswer[errorAnswer.index(rightAnswer)]
        answerOption = random.sample(errorAnswer,3) +[rightAnswer]
        random.shuffle(answerOption)
        testFile.write('%s. This is question %s\n'%(questionNum,allQuestion[questionNum]))
        for i in range(4):
            testFile.write('%s. %s\n'%('ABCD'[i],answerOption[i]))
        answerFile.write('%s'%('ABCD'[answerOption.index(rightAnswer)]))
    testFile.close()
    answerFile.close()

多重剪贴板

import sys,pyperclip,os,shelve
mcbShelf = shelve.open('mcb')
#save clipboard content
if len(sys.argv) == 3:
    if sys.argv[1] == 'save':
        mcbShelf[sys.argv[2]] = pyperclip.paste()
        print('%s is saved.'%(sys.argv[2]))
    elif sys.argv[1] == 'delete':
        del mcbShelf[sys.argv[2]]
        print('%s is delete.'%(sys.argv[2]))
elif len(sys.argv) == 2:
    if sys.argv[1] == 'list':
        print('list items:%s'%(str(list(mcbShelf.keys()))))
        pyperclip.copy(str(list(mcbShelf.keys())))
    elif sys.argv[1] == 'delete':
        print('All is delete')
        mcbShelf.clear()
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])
        print(mcbShelf[sys.argv[1]]+' is copied.')
    else:
        print('do not have items.')
mcbShelf.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值