🖼 人工智能学习总目录

🖼 《Python编程_从入门到实践》小结及目录

本章知识小结:

  • 1、f.read()、f.readlines()、f.write()
  • 2、words.split()
  • 3、try-except xxError-else
  • 4、import json、json.dump(numbers,f)、json.load(f)

1、读文件read()、逐行读readlines()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
filename = 'pi_million_digits.txt'

with open(filename) as file_object:
#file = file_object.read()
#for line in file[:3]:
lines = file_object.readlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")

2、写文件write()

1
2
3
4
5
6
# write_message.py
filename = 'programming.txt'

with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")

3、try-except xxError-else

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# word_count.py
def count_words(filename):
"""Count the approximate number of words in a file."""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)

4、存储数据json.dump()、json.load()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import json

numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)


filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f)

print(numbers)

5、小结

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
import json

# 是否有该用户
def get_stored_username():
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username

# 创建新用户
def get_new_username():
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f:
json.dump(username, f)
return username

# 欢迎用户
def greet_user():
username = get_stored_username()
if username:
print(f"Welcome back, {username}!")
else:
username = get_new_username()
print(f"We'll remember you when you come back, {username}!")

greet_user()