zoukankan      html  css  js  c++  java
  • 文件读写及实操项目

    读写文件

    文件系统-模块   什么是模块?例如下面random,如果需要生成随机数就需要引用random模块
                                                  >>> import random  #random随机函数
                                                  >>> secert = random.randint(1, 10)
                                                  >>> secert
                                                         3
    一、OS模块
    可以使程序运行在所有操作系统上
    将单个文件和路径上的文件名以字符串传递 使用os.path.join()返回文件路径的字符串
    >>> import os
    >>> os.path.join('user', 'bin', 'spam')
    'user\bin\spam'


    把文件名列表中的名称,添加到文件夹名称的末尾
    >>> myfile = ['1.csv', '2.doc', 'aaa.txt']
    >>> for filename in myfile:
        print(os.path.join('d:\User\xiu', filename))

        
    d:Userxiu1.csv
    d:Userxiu2.doc
    d:Userxiuaaa.txt

    OS模块关于文件/目录的相关函数

    os.getcwd()返回当前工作目录
    os.chdir()修改当前工作目录
    os.makedirs()创建新文件夹,多层
    os.listdir(path='')列举指定目录中文件
    os.mkdir()创建单层目录,如果该目录存在抛出异常
    os.rmdir(psth)删除空目录
    os.remove(path)删除子目录
    os.system(command)运行系统的shell    os.system('cmd')
    os.rename(old, new) 将文件old重名为new   os.rename('e:\A', 'e:\C')
    os.curdir指代当前目录 ‘.’
    os.pardir指代上一级目录‘..’



    二、OS.path模块关于文件/目录相关的函数

    os.path.basename('e:\B')去掉目录路径
    os.path.dirname(path)去掉文件名
    os.path.join('A', ' B', 'C')
    os.path.split('path')分割文件名与路径
    os.path.splitext()分离文件名与扩展名
    getsize(file)返回指定文件的尺寸,单位是字节
    os.path.getatime(file)返回指定文件最近的访问时间    time模块  gmtime()或localtime()
                 import time
                 time.gmtime(os.path.getatime(file))
    os.path.getctime(file)返回指定文件的创建时间
    os.path.abspath(path)返回参数的绝对路径的字符串
    os.path.isabs(path)如果参数绝对路径就返回true  ,如果参数是相对路径就返回false
                 备注:相对路径  相对于程序的当前工作目录
    os.path.relpath(path,start)返回从start路径到path的相对路径的字符串,如果没有start,
                 就使用当前工作目录作为开始路径
    os.path.exists(path)如果路径所指的文件或文件夹存在就返回true,否则返回false



                 
    三、文件读写过程
    在Python中,读写文件3个步骤:
                 1、调用open()函数,返回一个file对象
                 2、调用file对象的read()或write()方法
                 3、调用file对象的close()方法,关闭文件
                 例如:>>> myfile = open('C:\Users\xiu\Desktop\1.txt')
                       >>> mycontent = myfile.read()
                       >>> mycontent
                       '返回字符串'

                 例如:>>> myfile = open('C:\Users\xiu\Desktop\2.txt', 'w')
                       >>> myfile.write('hello world ')
                             12
                       >>> myfile.close()
                       >>> myfile = open('C:\Users\xiu\Desktop\2.txt', 'a')
                       >>> myfile.write('bacon is not a vegetable.')
                             25
                       >>> myfile.close()
                       >>> myfile = open('C:\Users\xiu\Desktop\2.txt')
                       >>> haha = myfile.read()
                       >>> myfile.close()
                       >>> print(haha)
                           hello world
                           bacon is not a vegetable.
                 'r'只读   'w'写   'a'添加模式


    四、shelve模块保存变量
    使用shelve模块将Python程序中的变量保存到二进制的shelf文件中
    import shelve
                 shelffile = shelve.open('mydata')
                 cats = ['hh', 'simon', 'stone']
                 shelffile['cats'] = cats
                 shelffile.close()
     
              ① shelffile = shelve.open('mydata')
                 shelffile['cats']
                 shelffile.close()
    shelf值有keys()和values()
              ② >>> shelffile = shelve.open('C:\Users\xiu\Desktop\3.txt')
                 >>> list(shelffile.keys())
                     ['cats']
                 >>> list(shelffile.values())
                     [['lilei', 'simon', 'stone']]
                 >>> shelffile.close()


    五、pprint.pformat()函数保存变量
    该函数将提供一个字符串,该文件将成为你自己的模块,如果你需要使用存储在其中的变量,就可以导入它
                import pprint
                 cats = [{'name': 'zeoo', 'name': 'lilei'}]
                 pprint.pformat(cats)
                 "[{'name': 'zeoo', 'name': 'lilei'}]"
                 fileobj = open('mycats.py', 'w')
                 fileobj.write('cats = ' + pprint.pformat(cats) + ' ')
                 fileobj.close()

                 import mycats
                 mycats.cats
                 [{'name': 'zeoo', 'name': 'lilei'}]
                 mycats.cats[0]
                 {'name': 'zeoo'}
                 mycats.cats[1]['name']
                 'lilei'


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

    程序思路
            第一步:将测验数据保存在一个字典中。创建一个脚本框架,并填入测验数据。创建一个名为randomQuizGenerstor.py文件
            第二步:创建测验文件,并打乱问题的次序

            第三步:创建答案选项

            第四步:将内容写入测验试卷和答案文件

    具体代码:方法①

    # -*- coding: UTF-8 -*-
    import random
    #创建3份不同的测验试卷
    #为每份试卷创建4个多重选择题,次序随机
    #为每个问题提供一个正确的答案和3个随机的错误答案,次序随机
    #将测验试卷写到3个文本文件中
    #这意味着代码需要坐下面的事
    #1、将州和对应的首府保存在一个字典中
    #2、针对测验文本文件和答案文本文件,调用open()、write()、close()
    #3、利用random.shuffle()随机调整问题和多重选项的次序
    capitals = {'alabama': 'montgomery', 'alaska': 'juneau', 'arizona': 'phoenix', 'arkansas':
    'little rock'}
    for quizNUM in range(4):
    # todo: crate the quiz and answer key files
    quizfile = open('capitalsquiz%s.txt' % (quizNUM + 1), 'a')
    answerKeyFile = open('capitalquiz_answer%s.txt' % (quizNUM + 1),'a')

    # todo: write out the header for the quiz
    quizfile.write('name: Date: Period: ')
    quizfile.write((' ' * 20) + 'state captials Quiz (form %s)' % (quizNUM + 1))
    quizfile.write(' ')

    # todo: shuffle the order of the states
    states = list(capitals.keys())
    random.shuffle(states)
    # todo: loop thyough all 4 ststes, making a question for each
    for questionNUM in range(4):
    correctAnswer = capitals[states[questionNUM]]
    wrongAnswers = list(capitals.values())
    del wrongAnswers[wrongAnswers.index(correctAnswer)]
    wrongAnswers = random.sample(wrongAnswers, 3)
    answerOptions = wrongAnswers + [correctAnswer]
    random.shuffle(answerOptions)

    quizfile = open('capitalsquiz%s.txt' % (quizNUM + 1), 'a')
    quizfile.write('%s. what is the capital of %s? ' % (questionNUM + 1, states[questionNUM]))
    for i in range(4):
    quizfile.write('%s. %s ' % ('ABCD'[i], answerOptions[i]))
    quizfile.write(' ')

    answerKeyFile = open('capitalquiz_answer%s.txt' % (quizNUM + 1), 'a')
    answerKeyFile.write('%s. %s ' % (questionNUM + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
    quizfile.close()
    answerKeyFile.close()
    方法②
    capitals = {'alabama': 'montgomery', 'alaska': 'juneau', 'arizona': 'phoenix', 'arkansas':
    'little rock'}
    for quizNUM in range(4):
    # todo: crate the quiz and answer key files
    with open('D:Users\xiuPycharmProjects\testquizcapitalsquiz%s.txt' % (quizNUM + 1), 'a') as r:
    # todo: write out the header for the quiz
    r.write('name: Date: Period: ')
    r.write((' ' * 10) + 'state captials Quiz (form %s)' % (quizNUM + 1))
    r.write(' ')

    # todo: shuffle the order of the states
    states = list(capitals.keys())
    random.shuffle(states)
    # todo: loop thyough all 4 ststes, making a question for each
    for questionNUM in range(4):
    correctAnswer = capitals[states[questionNUM]]
    wrongAnswers = list(capitals.values())
    del wrongAnswers[wrongAnswers.index(correctAnswer)]
    wrongAnswers = random.sample(wrongAnswers, 3)
    answerOptions = wrongAnswers + [correctAnswer]
    random.shuffle(answerOptions)

    with open('D:Users\xiuPycharmProjects\testquizcapitalsquiz%s.txt' % (quizNUM + 1), 'a') as f:
    f.write('%d. what is the capital of %s? ' % (questionNUM + 1, states[questionNUM]))

    for i in range(4):
    with open('D:Users\xiuPycharmProjects\testquizcapitalsquiz%s.txt' % (quizNUM + 1), 'a') as f:
    f.write('%s. %s ' % ('ABCD'[i], answerOptions[i]))

    with open('D:Users\xiuPycharmProjects\testquizcapitalsquiz%s.txt' % (quizNUM + 1), 'a') as f:
    f.write(' ')

    with open('D:Users\xiuPycharmProjects\testquizcapitalquiz_answer%s.txt' % (quizNUM + 1), 'a') as f:
    f.write('%s. %s ' % (questionNUM + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
     

     

  • 相关阅读:
    十二月第二周学习进度条
    《UML大战需求分析》阅读笔记4
    十二月第一周学习进度条
    十一月第四周学习进度条
    十一月第三周学习进度条
    十一月第二周学习进度条
    制作验证码(转)
    阅读笔记04
    课堂作业-购书问题
    阅读笔记03
  • 原文地址:https://www.cnblogs.com/tallshi/p/7839083.html
Copyright © 2011-2022 走看看