Read entire file
with open('pi_digits.txt') as file_object: contents = file_object.read()
print(contents.rstrip())
notes :
with Usage of : Make the file open and close properly .
rstrip() function : Eliminate blank lines
Use the contents of the document :
with open('test_files/pi_digits.txt') as file_object: lines =
file_object.readlines() pi_string = '' for line in lines: pi_string +=
line.strip() print(pi_string) print(len(pi_string))
notes : Error reading text file ,python Interprets all text as a string . If the reading is a number , Need to use int() Convert it to an integer , Using functions float() Convert it to a floating-point number .
Is birthday included in Pi
with open('pi_million_digits.txt') as file_object: lines =
file_object.readlines() pi_string = '' for line in lines: pi_string +=
line.strip() birthday = input("Enter your bithday:") if birthday in pi_string:
print("your birtday appears.") else: print("your birthday don't appear.")
#print(pi_string[:6] + "...") print(len(pi_string))
File write
filename = 'programing.txt' with open(filename,'a') as file_object:
file_object.write("I also love you.\n") file_object.write("I also love
programing.\n")
notes :open Several models of function :r: Read mode .w: Write mode a: Attachment mode , Other contents can be added on the original basis .
Write multiple lines \n: Line feed .
Use multiple files , And he didn't say a word when he failed .
try,
except Usage of : If try The code in the code block runs fine ,Python skip except Code block . If try Code running error ,python Will find such except modular , And run the code .
try, except,else In the module ,try Execution failed , function except, Run successfully , implement else modular .
def count_number(filename): try: with open(filename) as f_obj: contents =
f_obj.read() except FileNotFoundError: pass else: words = contents.split()
number_words = len(words) print("The novel " + filename +" has " +
str(number_words) + ".") filenames =
['alice.txt','sidd.txt','moby_dict.txt','little_women.txt'] for filename in
filenames: count_number(filename)
Decide which errors to report , Determined by user needs .
Store data
use json To store data .
import json def stored_username(): filename = 'username.json' try: with
open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError:
return None else: return username def get_new_name(): username = input("What's
your name?") filename = 'username.json' with open(filename, 'w') as f_obj:
json.dump(username, f_obj) return username def greet_user(): username =
stored_username() if username: print("welcome back," + username + "!") else:
username = get_new_name() print("We will be happy,when you come," + username +
"!") greet_user()
restructure
The code is divided into a series of functions to complete the specific work . This process is called refactoring .
Refactoring makes code clearer , Easier to understand , Easier to scale .
Technology