python学习7

Python-Import files

Every file has own path to access.

e.g.

UpDp6K.png

C:\Users\asweigart\Documents\project.docx

When comes to OS X and Linux, we use / to separate.

在 OS X 上,它们表示为新的文件夹,在/Volumes 文件夹下。在 Linux 上,它们表示为新的

文件夹,在/mnt(”mount”)文件夹下。同时也要注意,虽然文件夹名称和文件名在

Windows 和 OS X 上是不区分大小写的,但在 Linux 上是区分大小写的。

import files

os.path.join()

1
2
3
4
import os
os.path.join('usr', 'bin', 'spam')

#out:'usr\\bin\\spam'
1
2
3
4
5
6
7
8
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles: #add diferent filename after the same route as they are in the same folder
print(os.path.join('C:\\Users\\asweigart', filename))

#out:
#C:\Users\asweigart\accounts.txt
#C:\Users\asweigart\details.csv
#C:\Users\asweigart\invite.docx

current folder:

getcwd() : check which folder is the process in

chdir() :change the current folder (the folder must exist)

1
2
3
4
5
6
7
import os
os.getcwd()
#out:'C:\\Python34'

os.chdir('C:\\Windows\\System32')
os.getcwd()
#out:'C:\\Windows\\System32'

create new folder:os.makedirs()

1
2
import os
os.makedirs('C:\\delicious\\walnut\\waffles')

AP(absolute path) and relative path

UpyNct.png

processing with absolute path and relative path

os.path.abspath():show the absolute path(if something in the blanket,add it to the end of the absolute path, which means to open one folder or file in the original folder)

os.path.isabs():check wether it is absolute path

os.path.relpath(path,start):find the relative path from the start

os.path.dirname(path):return the string after the last \

os.path.split():separate the dirname and the basename by the last \

split() can also be used

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
os.path.abspath('.')
#out:'C:\\Python34'

os.path.abspath('.\\Scripts')
#out:'C:\\Python34\\Scripts'

os.path.isabs('.')
#out:False

os.path.isabs(os.path.abspath('.'))
#out:True

os.path.relpath('C:\\Windows', 'C:\\')
#out:'Windows'

path = 'C:\\Windows\\System32\\calc.exe'
os.path.basename(path)
#out:'calc.exe'

calcFilePath = 'C:\\Windows\\System32\\calc.exe'
os.path.split(calcFilePath)
#out:('C:\\Windows\\System32', 'calc.exe')

(os.path.dirname(calcFilePath), os.path.basename(calcFilePath))
#out:('C:\\Windows\\System32', 'calc.exe')

calcFilePath.split(os.path.sep)
#out:['C:', 'Windows', 'System32', 'calc.exe']

'/usr/bin'.split(os.path.sep)
#out:['', 'usr', 'bin']

others:

方法 说明
os.path.abspath(path) 返回绝对路径
os.path.basename(path) 返回文件名
os.path.commonprefix(list) 返回list(多个路径)中,所有path共有的最长的路径
os.path.dirname(path) 返回文件路径
os.path.exists(path) 如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。
os.path.lexists 路径存在则返回True,路径损坏也返回True
os.path.expanduser(path) 把path中包含的”“和”user”转换成用户目录
os.path.expandvars(path) 根据环境变量的值替换path中包含的”$name”和”${name}”
os.path.getatime(path) 返回最近访问时间(浮点型秒数)
os.path.getmtime(path) 返回最近文件修改时间
os.path.getctime(path) 返回文件 path 创建时间
os.path.getsize(path) 返回文件大小,如果文件不存在就返回错误
os.path.isabs(path) 判断是否为绝对路径
os.path.isfile(path) 判断路径是否为文件
os.path.isdir(path) 判断路径是否为目录
os.path.islink(path) 判断路径是否为链接
os.path.ismount(path) 判断路径是否为挂载点
os.path.join(path1[, path2[, …]]) 把目录和文件名合成一个路径
os.path.normcase(path) 转换path的大小写和斜杠
os.path.normpath(path) 规范path字符串形式
os.path.realpath(path) 返回path的真实路径
os.path.relpath(path[, start]) 从start开始计算相对路径
os.path.samefile(path1, path2) 判断目录或文件是否相同
os.path.sameopenfile(fp1, fp2) 判断fp1和fp2是否指向同一文件
os.path.samestat(stat1, stat2) 判断stat tuple stat1和stat2是否指向同一个文件
os.path.split(path) 把路径分割成 dirname 和 basename,返回一个元组
os.path.splitdrive(path) 一般用在 windows 下,返回驱动器名和路径组成的元组
os.path.splitext(path) 分割路径,返回路径名和文件扩展名的元组
os.path.splitunc(path) 把路径分割为加载点与文件
os.path.walk(path, visit, arg) 遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数
os.path.supports_unicode_filenames 设置是否支持unicode路径名

check the size and name

1
2
3
4
5
6
7
8
9
10
11
12
os.path.getsize('C:\\Windows\\System32\\calc.exe')
#out:776192

os.listdir('C:\\Windows\\System32')

#out:['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll', 'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']

totalSize = 0
for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
print(totalSize)
#out:1117846456

os.path.exists(path): check whether it exists

os.path.isfile(path): check whether it is a file

os.path.isdir(path): check whether it is a folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
os.path.exists('C:\\Windows')
#out:True

os.path.exists('C:\\some_made_up_folder')
#out:False

os.path.isdir('C:\\Windows\\System32')
#out:True

os.path.isfile('C:\\Windows\\System32')
#out:False

os.path.isdir('C:\\Windows\\System32\\calc.exe')
#out:False

os.path.isfile('C:\\Windows\\System32\\calc.exe')
#out:True

read the file

open()

windows:

1
helloFile = open('C:\\Users\\your_home_folder\\hello.txt')

OS X

1
helloFile = open('/Users/your_home_folder/hello.txt')

read()

1
2
3
4
helloContent = helloFile.read()
helloContent

#out:'Hello world!'

When, in disgrace with fortune and men’s eyes,

I all alone beweep my outcast state,

And trouble deaf heaven with my bootless cries,

And look upon myself and curse my fate,

1
2
3
4
5
sonnetFile = open('sonnet29.txt')
sonnetFile.readlines()

#out:
#[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my outcast #state,\n', And trouble deaf heaven with my bootless cries,\n', And look upon myself and #curse my fate,']

write()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
baconFile = open('bacon.txt', 'w')
baconFile.write('Hello world!\n')
#out:13

baconFile.close()
baconFile = open('bacon.txt', 'a')
baconFile.write('Bacon is not a vegetable.')
#out:25

baconFile.close()
baconFile = open('bacon.txt')
content = baconFile.read()
baconFile.close()
print(content)

#out:
#Hello world!
#Bacon is not a vegetable.

shelve

在交互环境下 under interactive environment

1
2
3
4
5
import shelve
shelfFile = shelve.open('mydata')
cats = ['Zophie', 'Pooka', 'Simon']
shelfFile['cats'] = cats
shelfFile.close()#don't forget to close the file
1
2
3
4
5
6
7
8
shelfFile = shelve.open('mydata')
type(shelfFile)
#out:<class 'shelve.DbfilenameShelf'>

shelfFile['cats']
#out:['Zophie', 'Pooka', 'Simon']

shelfFile.close()
1
2
3
4
5
6
7
8
shelfFile = shelve.open('mydata')
list(shelfFile.keys())
#out:['cats']

list(shelfFile.values())
#out:[['Zophie', 'Pooka', 'Simon']]

shelfFile.close()

pprint.pformat()

to show the content but not print

1
2
3
4
5
6
7
8
9
10
import pprint
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
pprint.pformat(cats)
#out:"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"

fileObj = open('myCats.py', 'w')
fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
#out:83

fileObj.close()

import can be used toimport files

1
2
3
4
5
6
7
8
import myCats
myCats.cats
#out:[{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]

myCats.cats[0]
{'name': 'Zophie', 'desc': 'chubby'}
myCats.cats[0]['name']
#out:'Zophie'

example

You want to create 35 different quiz files for 35 students tocheck their knowledge about sates and their capitals in America. Every quiz should include 50 multiple choice questions, and they should be in different order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#! python3
# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.

import random

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



# Generate 35 quiz files.
for quizNum in range(35):

# TODO: Create the quiz and answer key files.
# TODO: Write out the header for the quiz.
# TODO: Shuffle the order of the states.
# TODO: Loop through all 50 states, making a question for each.
# Create the quiz and answer key files.

quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')

# Write out the header for the quiz.

quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')

# Shuffle the order of the states.

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




# TODO: Loop through all 50 states, making a question for each.
# 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)] #delete the correct answer
wrongAnswers = random.sample(wrongAnswers, 3) #get three of them randomly
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions) #change the order of the options randomly




# TODO: Write the question and answer options to the quiz file.
# TODO: Write the answer key to a file.
# Loop through all 50 states, making a question for each.

for questionNum in range(50):

# Write the question and the answer options to the quiz file.

quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1,states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')

# Write the answer key to a file.

answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()

Name:

Date:

Period:

​ State Capitals Quiz (Form 1)

  1. What is the capital of West Virginia?

A. Hartford

B. Santa Fe

C. Harrisburg

D. Charleston

  1. What is the capital of Colorado?

A. Raleigh

B. Harrisburg

C. Denver

D. Lincoln

… …