输入输出
# 输入输出
# 输入
## 回文测试
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input("Enter text: ")
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
[::-1]
, 倒序反转字符串
# 文件写
poem ="""
早发白帝城
唐 李白
朝辞白帝彩云间,千里江陵一日还。
两岸猿声啼不住,轻舟已过万重山。
"""
f = open('poem.txt', 'w',encoding='utf-8')
f.write(poem)
f.close()
f = open('poem.txt', 'w',encoding='utf-8')
, 文件写f.write(poem)
, 文件写入内容
# 文件输出
f = open('poem.txt', 'r', encoding='utf-8')
while True:
line = f.readline()
## 文件结束
if len(line) == 0:
break
## readline 已经有换行符
print(line, end='')
f.close()
f = open('poem.txt', 'r', encoding='utf-8')
, 文件读line = f.readline()
, 文件一行行读
# with
with open('poem.txt', 'r', encoding='utf-8') as f:
while True:
line = f.readline()
if len(line) == 0:
break
print(line.strip())
with open('poem.txt', 'r', encoding='utf-8') as f:
, 语法糖写法, 可不容易出错
# StringIO
在内存中读写Str
# 读
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
f = StringIO()
,f.write(str)
, 像文件一样写入strf.getvalue()
, 获得写入的str
# 写
from io import StringIO
f1 = StringIO('Hello!\nHi\nGoodbye!\n')
while True:
s = f1.readline()
if s == '':
break
print(s.strip())
f1 = StringIO('Hello!\nHi\nGoodbye!\n')
,用一个str 初始化 StringIO,s = f1.readline()
,像文件一样读取
# 持久化
import pickle
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
f = open(shoplistfile, 'wb')
## 转储对象至文件
pickle.dump(shoplist, f)
f.close()
f = open(shoplistfile, 'rb')
## 从文件中载入对象
storeList = pickle.load(f)
print(storeList)