10-1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
file = 'learning.txt'
with open(file) as file_object:
contents = file_object.read()
print(contents.rstrip())
with open(file) as file_object:
for lines in file_object:
print(lines.rstrip())
with open(file) as file_object:
lin = file_object.readlines()
for li in lin:
print(li.rstrip())
10-4
#!/usr/bin/env python
# -*- coding:utf-8 -*-
file = 'guest.txt'
with open(file,'a') as filename:
while True:
records = input("please enter your name")
if records!='q':
print('hello ' + records)
filename.write(records)
else:
break
with open(file) as filename:
xianshi = filename.read()
print(xianshi)
用open打開一個文件,用w寫入模式,是沒有權限read得,得用w+模式。
用write寫入字符,但是此時沒有真正得寫入,而是在內存中,a.close()以後再read才能讀到數據
10-5
#!/usr/bin/env python
# -*- coding:utf-8 -*-
file = 'guest.txt'
with open(file,'a+') as filename:
while True:
question = input("why do you like coding")
if question=='q':
break
filename.write(question + '\n')
filename.seek(0)
reading = filename.read()
print(reading)
10-6
#!/usr/bin/env python
# -*- coding:utf-8 -*-
try:
number1 = input('please enter first number:')
number2 = input('please enter second number:')
number1 = int(number1)
number2 = int(number2)
except ValueError:
print('please enter number')
else:
print(number1+number2)
10-7
#!/usr/bin/env python
# -*- coding:utf-8 -*-
while True:
try:
number1 = input('please enter first number:')
number2 = input('please enter second number:')
number1 = int(number1)
number2 = int(number2)
except ValueError:
print('please enter number')
else:
print(number1+number2)
break
10-8
#!/usr/bin/env python
# -*- coding:utf-8 -*-
try:
file1 = 'cats.txt'
file2 = 'dos.txt'
with open(file1,'r') as f1:
read1 = f1.read()
print(read1+'\n')
with open(file2, 'r') as f2:
read2 = f2.read()
print(read2)
except FileNotFoundError:
print("this file is not found")
10-9
#!/usr/bin/env python
# -*- coding:utf-8 -*-
try:
file1 = 'cats.txt'
file2 = 'dos.txt'
with open(file1,'r') as f1:
read1 = f1.read()
print(read1+'\n')
with open(file2, 'r') as f2:
read2 = f2.read()
print(read2)
except FileNotFoundError:
pass
10-10
#!/usr/bin/env python
# -*- coding:utf-8 -*-
with open('bood.txt') as book:
book_word = book.read()
print(book_word.count('the'))