用戶輸入內(nèi)容
def reverse(text):
return text[::-1]
# 判斷是否為回文,原文本和反轉(zhuǎn)后的文本是否相同
def isPalindrome(text):
return text == text
# 獲取用戶輸入內(nèi)容
# 按下Enter鍵之后睹晒,input返回用戶的輸入內(nèi)容
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
文件
我們可以創(chuàng)建一個file
類對象趟庄,通過它的read
、readline
伪很、write
等方法打開或使用文件戚啥。
# 文件內(nèi)容
poem = ''' \
wwwwwwwwwwwwww
wwwwwwwwwww
wwwwwwwwwwwwwwww
text
xxoo
ppp
qewwwfwf
'''
# 創(chuàng)建文件類對象 f
# open 打開文件以編輯,w為writing是掰,編輯模式
f = open('/Users/a1/Desktop/test.txt','w')
# 向文件中寫入內(nèi)容
f.write(poem)
# 關(guān)閉文件
f.close()
# 如果沒有特別指定 虑鼎,使用open時默認(rèn)采取的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
操作是成對出現(xiàn)的。
w
寫入模式 键痛;r
讀取模式炫彩;a
追加模式;t
文本模式絮短;b
二進(jìn)制模式
Pickle
通過Pickle
我們可以將任何純Python
對象存儲到一個文件中江兢,并在適當(dāng)?shù)臅r候取回使用。這種操作叫做持久地存儲對象丁频,也可以叫做數(shù)據(jù)持久化杉允。
import pickle
import os
# 對象所存儲到的文件名
shoplistfile = '/Users/a1/Desktop/text.data'
# 需要存儲的對象數(shù)據(jù)
shoplist = ['apple','xigua','carrot']
# 創(chuàng)建文件操作對象 打開文件
# 寫入文件
file = open(shoplistfile,'wb')
# 開始轉(zhuǎn)存文件
pickle.dump(shoplist,file)
# 關(guān)閉文件操作對象
file.close()
# 刪除已存儲的對象數(shù)據(jù)
del shoplist
# 打開存儲對象的文件,讀取內(nèi)容
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()
# 讀取文件中的內(nèi)容
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