用户输入内容
def reverse(text):
return text[::-1]
# 判断是否为回文,原文本和反转后的文本是否相同
def isPalindrome(text):
return text == text
# 获取用户输入内容
# 按下Enter键之后,input返回用户的输入内容
something = input("Enter text:")
if isPalindrome(something):
print("It is palindrome.")
else:
print("It is not palindrome.")
控制台
Enter text:wertrew
It is palindrome.
Process finished with exit code 0
文件
我们可以创建一个file
类对象,通过它的read
、readline
、write
等方法打开或使用文件。
# 文件内容
poem = ''' \
wwwwwwwwwwwwww
wwwwwwwwwww
wwwwwwwwwwwwwwww
text
xxoo
ppp
qewwwfwf
'''
# 创建文件类对象 f
# open 打开文件以编辑,w为writing,编辑模式
f = open('/Users/a1/Desktop/test.txt','w')
# 向文件中写入内容
f.write(poem)
# 关闭文件
f.close()
# 如果没有特别指定 ,使用open时默认采取的r read模式
f = open('/Users/a1/Desktop/test.txt')
while True:
# readline 读取文件的一整行
line = f.readline()
# 零长度知识 类似C语言中的文件尾 EOF
if len(line) == 0:
break
print(line,end='')
f.close()
注意:
file
的open
操作和close
操作是成对出现的。
w
写入模式 ;r
读取模式;a
追加模式;t
文本模式;b
二进制模式
Pickle
通过Pickle
我们可以将任何纯Python
对象存储到一个文件中,并在适当的时候取回使用。这种操作叫做持久地存储对象,也可以叫做数据持久化。
import pickle
import os
# 对象所存储到的文件名
shoplistfile = '/Users/a1/Desktop/text.data'
# 需要存储的对象数据
shoplist = ['apple','xigua','carrot']
# 创建文件操作对象 打开文件
# 写入文件
file = open(shoplistfile,'wb')
# 开始转存文件
pickle.dump(shoplist,file)
# 关闭文件操作对象
file.close()
# 删除已存储的对象数据
del shoplist
# 打开存储对象的文件,读取内容
file = open(shoplistfile,'rb')
# load用来接收返回的对象
storedlist = pickle.load(file)
print('The object data is:',storedlist)
控制台
The object data is: ['apple', 'xigua', 'carrot']
Process finished with exit code 0
Unicode
我们可以通过u'非英文字符'
来表示Unicode
类型。
import io
import os
source = '/Users/a1/Desktop/test.data'
# io.open打开文件 指定读取模式为wt 编码为 utf-8
file = io.open(source,"wt",encoding="utf-8")
file.write(u'eeeeeee')
file.close()
# 读取文件中的内容
text = io.open(source,encoding='utf-8').read()
print('The file content is :',text)
控制台
The file content is : eeeeeee
Process finished with exit code 0