文件路径
import os
path = os.path.join('c:\\','user','python')
file_name_dir = os.path.join(path,file_name)
os.getcwd() / os.chdir() / os.makedirs() /
os.getcwd():获取当前工作目录
os.chdir:改变当前工作目录
os.makedirs():创建目录
绝对路径/相对路径
os.path.abspath(path):返回path的绝对路径
os.path.isabs(path):查询是否为绝对路径 返回True
获取路径和文件名
os.path.dirname(path)
os.path.basename(path)
获取文件大小
os.path.getsize()
例子
注意:
通过每一级print可以看到过程
os.listdir(path):命令在os模块中,而不是path模块中
os.path.exists(path) :判断文件或路径存是否存在
import os
path = 'C:\\python\\file1'
# print(path)
if os.path.exists(path): #判断路径是否存在
file_names = os.listdir(path) #获取文件目录下的文件名列表
# print(file_names)
size = 0
for file_name in file_names:
# print(file_name)
file_name_path = os.path.join(path,file_name) #获得最终的路径
# print(file_name_path)
size += os.path.getsize(file_name_path)
print(size)
os.path.dirname(Path)
os.path.basename(Path)
项目:生成随机的测验试卷文件
第一次写
'''
假如你是一位地理老师,班上有35 名学生,你希望进行美国各州首府的一个
小测验。不妙的是,班里有几个坏蛋,你无法确信学生不会作弊。你希望随机调整
问题的次序,这样每份试卷都是独一无二的,这让任何人都不能从其他人那里抄袭
答案
'''
import random
import os
#创建一个关于各个州和首府的字典
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'}
#创建35分试卷、答案
dir_path = 'c:\\python\\file'
for paper_number in range(60):
exam_paper_path = os.path.join(dir_path,'paper number%s.txt' %(paper_number))
answer_paper_path = os.path.join(dir_path,'answer number%s.txt'%(paper_number))
# print(type(exam_paper_path))
# print(exam_paper_path)
# print(answer_paper_path )
exam_paper = open(exam_paper_path,'w')
answer_paper = open(answer_paper_path,'w')
exam_paper.write('\n\ngrade:\nclass:\t\t\t\tname:\n'.ljust(50))
#循环创建50个题
states = list(capitals.keys())
random.shuffle(states)
for ques_num in range(len(capitals)):
question = states.pop()
right_answer = capitals[question]
temp_capitals = capitals.copy()
del temp_capitals[question]
# print(capitals)
wrong_answers = random.sample(list(temp_capitals.values()),3)
answers = [right_answer] + wrong_answers
random.shuffle(answers)
# print(answers)
# print('the %s state\' captail is:( )'%(question))
# print('\tA.%s B.%s C. %s D. %s'%(answers[0],answers[1],answers[2],answers[3]))
exam_paper.writelines('\nthe %s state\' captail is:( )\n'%(question))
exam_paper.writelines('\tA.%s B.%s C. %s D. %s\n'%(answers[0],answers[1],answers[2],answers[3]))
answer_paper.writelines('number %s answer is %s\n'%(ques_num,question))
exam_paper.close()
answer_paper.close()
第二次写
import logging
import random
import os
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
'''
假如你是一位地理老师,班上有35 名学生,你希望进行美国各州首府的一个
小测验。不妙的是,班里有几个坏蛋,你无法确信学生不会作弊。你希望随机调整
问题的次序,这样每份试卷都是独一无二的,这让任何人都不能从其他人那里抄袭
答案。当然,手工完成这件事又费时又无聊。好在,你懂一些Python。
'''
#各个州首府的字典
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'}
logging.debug('start of program')
#first creat 50 files for test paper
students =50
dir_path = 'c:\\python\\file'
for student in range(students):
test_full_path = os.path.join(dir_path,'Test Paper_%s.txt'%(student+1))
answer_full_path = os.path.join(dir_path,'Answer_%s.txt'%(student+1))
test_paper = open(test_full_path,'w+')
answer_paper = open(answer_full_path,'w')
# logging.debug('the path is %s'%os.path.join(dir_path,'Test Paper_%s.txt'%(student+1)))
# logging.debug('the file is exist = %s'%(os.path.exists(os.path.join(dir_path,'Test Paper_%s.txt'%(student+1)))))
#file creat done, print student info
test_paper.writelines('class:\t\tname:\n\tage:\n')
#student info completed,now print question and answer
states = list(capitals.keys())
random.shuffle(states)
# logging.debug('the states is %s'%states)
for state in states: #state is the question
right_answer = capitals[state]
states.remove(state)
capitals_copy = capitals.copy()
del capitals_copy[state]
answers = random.sample(list(capitals_copy.values()),3) + [right_answer]
logging.debug('%s\'s captial is %s should in %s'%(state,right_answer,answers))
random.shuffle(answers)
#we get the question(state) and answers, but the right answer is the last one,
# we should random answers and print it to test_paper
test_paper.write('which is %s\' capital. ( ) \n'%state)
answer_paper.write(right_answer)
for i in range(4):
test_paper.write('%s.%s\n'%(['A','B','C','D'][i],answers[i]))
test_paper.close()
answer_paper.close()
第三次写
import logging
import random
import os
import datetime
'''
假如你是一位地理老师,班上有35 名学生,你希望进行美国各州首府的一个
小测验。不妙的是,班里有几个坏蛋,你无法确信学生不会作弊。你希望随机调整
问题的次序,这样每份试卷都是独一无二的,这让任何人都不能从其他人那里抄袭
答案。当然,手工完成这件事又费时又无聊。好在,你懂一些Python。
'''
#各个州首府的字典
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'}
#先生成50个试卷文件,50个答案文件
#需要的变量,
#学生数量 student_num
#试卷文件路径 path
#试卷文件名 test_paper_1,生成的文件名有序号,所以循环 len()比较好
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
student_num = 50
path = 'c:\\python\\file\\'
for file_num in range(student_num):
test_paper = open((path + 'test_paper_%s.txt'%(file_num+1)),'w')
answer_paper = open((path + 'answer_%s.txt'%(file_num+1)),'w')
test_paper.write('class:\t\tname:\n')
#生成测试题
#问题关键字 州名字 states[ques_num]
#题号 ques_num 需要用到题号,使用len()比较好
#正确答案 right_answer
#选择项 options 三个错误答案 + 正确答案
states = list(capitals.keys())
random.shuffle(states)
for ques_num in range(len(states)):
answers = list(capitals.values())
# logging.debug(len(answers))
right_answer = capitals[states[ques_num]]
answers.remove(right_answer)
# logging.debug(len(answers))
options = random.sample(answers,3) + [right_answer]
# logging.debug(len(options))
random.shuffle(options)
# logging.debug(options)
test_paper.write('\n%s.which is the captain of %s\n\n'%((ques_num+1),states[ques_num]))
for i in range(4):
test_paper.write('%s,%s\n'%(['A','B','C','D'][i],options[i]))
answer_paper.write('%s-%s\n'%(ques_num+1,['A','B','C','D'][options.index(capitals[states[ques_num]])]))
logging.debug('file exited %s'%(os.path.exists((path + 'test_paper_%s.txt'%(student_num)))))
'''