Reading from a File
同一目录下:
file_name = 'a.txt'
with open(file_name) as file_object:
contents = file_object.read() # string
"""
读取同一目录下的a.txt文件
"""
open函数打开文件,把文件读取到内存中,若不用close关闭文件,会导致文件容易被篡改。
使用with可以保证在程序跳出with时关闭文件,更为安全。
Relative Path
从python程序文件所在目录开始的路径:
with open('text_files/filename.txt') as file_object: # Linux or OSX
pass
with open('text_files\filename.txt') as file_object: # Windows
pass
Absolute Path
右键——属性——路径,即可得到绝对路径。
r""消除歧义。
# Linux or OSX
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
pass
# Windows
file_path = r'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
pass
File Mode
‘r’:只读模式
只读,不可写。打开时光标自动定位到开头位置。
‘r+’:读写模式
可读可写,写与读不分先后。写从光标开始,会覆盖原有内容,而光标通过读取决定。打开文件时光标在开头位置。
‘w’:只写模式
打开即默认创建一个新的空文件,若打开的是已有文件,则清空文件,且只能执行写操作。
‘w+’:写读模式
先写后读。打开文档即清空原内容,从文档开头写起,写完后光标自动移到文档末尾,此时进行读取,内容为空。需要将光标移到首位,f.seek(0)。如果以“w+”模式打开,先进行读操作,读到的内容也是为空,因为打开即被清空了。
‘a’:追加模式
只写,不可读。打开时不清空原文档,光标自动定位到文档末尾。
‘a+’:追加写读模式
先写后读。追加在原文档末尾,不会清空原内容,写完后光标移到文档末尾,此时进行读取,内容为空。需要将光标移到首位,f.seek(0)。如果以“a+”模式打开,先进行读操作,读到的内容也是为空,因为打开即把光标定位在文档末尾。
Reading Line by Line
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
"""
3.1415926535
8979323846
2643383279
"""
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines() #List
for line in lines:
print(line.rstrip())
"""
3.1415926535
8979323846
2643383279
"""
Writing to a File
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
FileNotFoundError
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
"""
Sorry, the file alice.txt does not exist.
"""
Try-Except-Else
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# Count the approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename
+ " has about " + str(num_words) + " words.")
"""
找不到文件---except语句
找到文件---else语句
"""
JSON
dump and download
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
"""
将numbers写入numbers.json
"""
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
"""
读取numbers.json中的数据并存入numbers
"""
Organizing Files
通过os.path.join快速生成文件路径
import os
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(os.path.join(r'C:\Users\asweigart', filename))
"""
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
"""
The Current Working Directory
切换当前的工作目录
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
>>> os.chdir(..)
"""返回上级目录"""
创建文件夹
>>> import os
>>> os.makedirs(r'C:\delicious\walnut\waffles')
List All Files
>>> os.listdir(directory)
Test
比较程序结果与预期结果:
"""被测试程序"""
def get_formatted_name(first, last):
full_name = first + ' ' + last
return full_name.title()
"""对拍程序"""
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
def test_first_last_name(self): # should start with test_
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
assert methods:
assertEqual(a, b) # Verify that a == b
assertNotEqual(a, b) # Verify that a != b
assertTrue(x) # Verify that x is True
assertFalse(x) # Verify that x is False
assertIn(item, list) # Verify that item is in list
assertNotIn(item, list) # Verify that item is not in list
setUp(self)减少创建重复实例,相当于__init__():
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()