Python新手学习(七):读写文件

9.读写文件(2024/4/17-4/18)
1)文件名和路径
  文件名中的正斜杠和反斜杠,在win、macOS和Linux中的不同。
  使用/运算符连接文件路径
  当前工作目录 Path.cwd()
  主目录:Path.home()
  创建新文件夹:os.makedirs() Path.mkdir()
  绝对路径和相对路径的处理:
    Path.is_absolute()
    os.path.abspath()
    os.path.isabs()
    os.path.relpath()
  取得文件路径的各部分属性值
    Path().anchor 根文件夹
    Path().drive 驱动器,只用于Windows
    Path().parent 父级目录
    Path().name 文件名 Path().stem主干名 Path().suffix 扩展名
    Path().parents() 取父目录的各级
    os.path.basename() 取文件名
    os.path.dirname() 取路径名
    os.path.split() 生成目录名和文件名的元组
    str.split(os.sep) 可以对路径名进行全分解为列表
  查看文件大小和文件夹内容
    os.path.getsize() 返回文件字节数
    os.listdir() 展目录下的文件名列表
  使用通配符模式修改文件列表
    Path().glob() 返回列出的文件名生成器对象。
  检查路径的有效性
    path().exists() 路径存在否    
    Path().is_file() 是文件
    Path().is_dir() 是目录
    os.path.exists() os.path.isfiel() os.path.isdir()
2)文件读写过程
  纯文本文件和二进制文件。
  简单写入和读出操作:
    write_text()  read_text() 类似于echo cat。
    open() 打开文件,生成文件名柄,有’w’和‘a’模式
    read() 读取文件到字符串中
    readlines() 将文件读到字符串的列表中
    write() 写入文件
    close() 关闭文件。
3)用shelve模块保存变量
  shelve模块引入 import shelve
    shelve.open()
    shelFile[‘key’]=value
    shelve.close()
  shelve模块主要用于将系统变量以二进制形式保存到文件中。
4)pprint.pformat()函数保存变量
  以文本列表形式保存变量
5)项目:生成随机的测验试卷文件
  测试程序:test_901.py

#! python3
# randomQuizGenerator.py - Creates quizzes with questions and answers in 
# random order, along with the answer key.

import random,os

# The quiz data. Keys are states and vlues are their capitals.
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'}

os.chdir('d:/temp/waffle')

# Generate 35 quiz files.
for quizNum in range(35):
    # Create the Quiz and answer key files.
    quizFile = open (f'capitalsquiz{quizNum + 1}.txt','w')
    answerKeyFile =open(f'capitalsquiz_answers{quizNum+1}.txt','w')
    # Write out the header for the quiz.
    quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
    quizFile.write((' ' * 20) + f'State Capitals Quiz (Form{quizNum +1})')
    quizFile.write('\n\n')

    # Shuffle the order of the states.
    states = list (capitals.keys())
    random.shuffle(states)

    # Loop through all 50 states, making a question for each.
    for questionNum in range(50):
        
        # Get right and wrong answers.
        correctAnswer = capitals[states[questionNum]]
        wrongAnswers = list(capitals.values())
        del wrongAnswers[wrongAnswers.index(correctAnswer)]
        wrongAnswers = random.sample(wrongAnswers,3)
        answerOptions = wrongAnswers + [correctAnswer]
        random.shuffle(answerOptions)

        # Write the question and the answer options to the quiz file.
        quizFile.write(f'{questionNum +1}. What is the capital of {states[questionNum]}?(    )\n')
        for i in range(4):
            quizFile.write(f"   {'ABCD'[i]}.{ answerOptions[i]}\n")
        quizFile.write('\n')

        #Write the answer key to a file.
        if questionNum > 0 and questionNum % 10 == 0:
            answerKeyFile.write('\n')
        answerKeyFile.write(f"{questionNum + 1}.{'ABCD'[answerOptions.index(correctAnswer)]} ")
    quizFile.close()
    answerKeyFile.close()

6)项目:创建可更新的多重剪贴板
  测试程序:test_901.py

#! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage:    py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
#           py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
#           py.exe mcb.pyw list - Loads all keywords to clipboard.

import shelve,pyperclip,sys

mcbShelf = shelve.open('d:/temp/waffle/mcb')

# Save clipboard content.
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif len(sys.argv) == 2:
    # List keywords and load content.
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值