1 文件读写操作(适用于纯文本文件)

纯文本文件只包含基本文字字符,不包含字体,大小和颜色信息。

读取文件内容:

import oshelloFile = open('C:\\Users\\Administrator\\Desktop\\hello.txt')helloContent = helloFile.read()print('%s' %helloContent)

写入文件内容:

Python 允许你将内容写入文件,方式与print()函数将字符串“写”到屏幕上类似。但是,如果打开文件时用读模式,就不能写入文件。你需要以“写入纯文本模式”或“添加纯文本模式”打开该文件,或简称为“写模式”和“添加模式”。

写模式:会从头开始写,会覆盖原来有的文件。将'w'作为第二个参数传递给open(),以写模式打开该文件。

添加模式:在文本的末尾添加文本,将'a'作为第二个参数传递给open(),以添加模式打开该文件。

如果传递给 open()的文件名不存在,写模式和添加模式都会创建一个新的空文件。在读取或写入文件后,调用close()方法,然后才能再次打开该文件。

import os##读文件helloFile = open('C:\\Users\\Administrator\\Desktop\\hello.txt')helloContent = helloFile.read()print
('%s' %helloContent)##写文件## 1)覆盖模式baconFile = open('C:\\Users\\Administrator\\Desktop\\bacon.txt','w')baconFile.
write('Hello world!\n')baconFile.close()## 2)末尾文本添加模式baconFile = open('C:\\Users\\Administrator\\Desktop\\bacon.txt','a')
baconFile.write('Bacon is not a vegetable.\n')baconFile.close()##读出文件中的内容baconFile = open('C:\\Users\\Administrator\\Desktop\\bacon.txt')
content = baconFile.read()baconFile.close()print(content)

Python读取文件进行批量字符串从a转换为b python从文本中读取变量值_Desktop

用shelve模块保存变量:

利用shelve 模块,你可以将Python 程序中的变量保存到二进制的shelf 文件中。

import shelve##写操作,没有当前文件会自动创建相应文件shelfFile = shelve.open('C:\\Users\\Administrator\\Desktop\\test\\mydata')cats = ['Zophie','Pooks','Simon']shelfFile['cats'] = catsshelfFile.close()##读操作shelfFile = shelve.open('C:\\Users\\Administrator\\Desktop\\test\\mydata')c = type(shelfFile)print(c)shelfFile = shelfFile['cats']print(shelfFile)##读二进制文件的文件名和文件内容shelfFile = shelve.open('C:\\Users\\Administrator\\Desktop\\test\\mydata')keysname = print(list(shelfFile.keys()))print(keysname)valuename = print(list(shelfFile.values()))print(valuename)shelfFile.close()

运行上述的代码,会在当前路径下创建三个新文件:mydata.bak、mydata.data、mydata.dir

Python读取文件进行批量字符串从a转换为b python从文本中读取变量值_Desktop_02

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

注:字典中的key()列表和value()列表# 定义一个字典

dic = {'剧情': 11, '犯罪': 10, '动作': 8, '爱情': 3, '喜剧': 2, '冒险': 2, '悬疑': 2, '惊悚': 2, '奇幻': 1}#通过list将字典中的keys和values转化为列表keys = list(dic.keys())values = list(dic.values())# 结果输出print("keys列表为:",end='')print(keys)print("values列表为:",end='')print(values)

Python读取文件进行批量字符串从a转换为b python从文本中读取变量值_写入文件_03

shelve的用法读写可以同时进行,不同于前面的open()打开方法

2 读写操作对应的一个小项目

假如你是一位地理老师,班上有35 名学生,你希望进行美国各州首府的一个小测验。不妙的是,班里有几个坏蛋,你无法确信学生不会作弊。你希望随机调整问题的次序,这样每份试卷都是独一无二的,这让任何人都不能从其他人那里抄袭答案。

程序需要做的事情:

1)创建35 份不同的测验试卷。

2)为每份试卷创建50 个多重选择题,次序随机。

3)为每个问题提供一个正确答案和3 个随机的错误答案,次序随机。

4)将测验试卷写到35 个文本文件中。

5)将答案写到35 个文本文件中。

程序中需要使用到的python的操作有:

1)将州和它们的首府保存在一个字典中。

2)针对测验文本文件和答案文本文件,调用open()、write()和close()。

3)利用random.shuffle()随机调整问题和多重选项的次序。

import random#定义一个字典, key()为州名,  value()为首府名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', 'WestVirginia': 'Charleston', 'Wisconsin': 'Madison', '
Wyoming': 'Cheyenne'}#创建35个文件for quizNum in range(35):# 创建一个问题文件夹 和 他的答案    quizFile = open('C:\\Users\\Administrator\\Desktop\\
random_test\\capitalsquiz%s.txt' %(quizNum+1),'w')    answerKeyFile = open('C:\\Users\\Administrator\\Desktop\\random_test\\capitalsquiz_answers%s.
txt' %(quizNum+1),'w')# 写入试卷的头格式    quizFile.write('Name:\n\nData:\n\nPeriod:\n\n')    quizFile.write((' ' * 20) + 'State Captitals Quiz 
(Form %s)' %(quizNum + 1))    quizFile.write('\n\n')# 随机排列    states = list(capitals.keys())  #现在state[]列表里包含了50个省会的城市名   
 random.shuffle(states)          #random.shuffle()函数,将列表中的元素随机排序#3、创建答案选项:#下面开始随机生成3个错误答案和1个正确答案。
这4个答案在每一个文件中的顺序都是随机的    for questionNum in range(50):        correctAnswer = capitals[states[questionNum]] 
 #将省名对应的省会的名字,赋给correctAnswer        wrongAnswers  = list(capitals.values()) #将字典中所有的首府名复制出来    
    #.index()函数, 相当于find()函数,在列表中找出这个字符串对应的序号。        del wrongAnswers[wrongAnswers.index(correctAnswer)]
 #在所有答案中,删除正确答案        wrongAnswers = random.sample(wrongAnswers,3) #然后在错误的答案中随机选择出3个错误的答案    
    answerOptions = wrongAnswers + [correctAnswer]  #最终的选项列表包含了,三个错误答案和一个正确答案        random.shuffle(answerOptions)
   #将得到的四个答案列表进行随机排序#4、将第三步创建的答案选项写入到文件中        quizFile.write('%s. What is the capital of %s?\n'
 %(questionNum+1,states[questionNum]))        for i in range(4):            #'ABCD'[i]将'ABCD'看成一个数组,每次循环中就是求A,B,C,D    
        quizFile.write(' %s. %s\n' %('ABCD'[i],answerOptions[i]))        quizFile.write('\n')# Write the answer key to a file.      
  #从ABCD中,找到正确答案对应的下标,将正确答案对应的下标写入到答案对应的文件中        answerKeyFile.write('%s. %s\n' %(questionNum+1, '
ABCD'[answerOptions.index(correctAnswer)]))    quizFile.close()    answerKeyFile.close()
运行结果:

Python读取文件进行批量字符串从a转换为b python从文本中读取变量值_对同一变量进行读写操作_04