您的位置:首页 > 编程语言 > Python开发

(八)《A Byte of Python》——输入与输出

2018-01-17 20:23 323 查看
        如果希望获取用户的输入内容,并向用户打印出一些返回的结果。我们可以分别通过 input() 函数与 print 函数来实现这一需求。对于输入,我们还可以使用 str (String,字符串) 类的各种方法。而另一个常见的输入输出类型是处理文件。
 1. 用户输入内容
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")
$ python3 io_input.py
Enter text: sir
No, it is not a palindrome
$ python3 io_input.py
Enter text: madam
Yes, it is a palindrome
$ python3 io_input.py
Enter text: racecar
Yes, it is a palindrome
2. 文件
        可以通过创建一个属于 file 类的对象并适当使用它的read 、readline 、write方法来打开或使用文件,并对它们进行读取或写入。读取或写入文件的能力取决于你指定以何种方式打开文件。完成了文件后,可以调用 close 告诉 Python已完成了对该文件的使用。
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
# 打开文件以编辑('w'riting)
f = open('poem.txt', 'w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close()
# 如果没有特别指定,
# 将假定启用默认的阅读('r'ead) 模式
f = open('poem.txt')
while True:
line = f.readline()
# 零长度指示 EOF
if len(line) == 0:
break
# 每行(`line`) 的末尾
# 都已经有了换行符
#因为它是从一个文件中进行读取的
print(line, end='')
# 关闭文件
f.close()
$ python3 io_using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
        打开模式可以是阅读模式('r' ) ,写入模式('w' ) 和追加模式('a' ) 。我们还可以选择是通过文本模式('t' ) 还是二进制模式('b' ) 来读取、写入或追加文本。在默认情况下, open() 会将文件视作文本(text) 文件,并以阅读(read) 模式打开 。
3. Pickle
        将任何纯 Python 对象存储到一个文件中,并在稍后将其取回。这叫作持久地(Persistently) 存储对象。import pickle
# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()
# Destroy the shoplist variable
del shoplist
# Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)
$ python io_pickle.py
['apple', 'mango', 'carrot']
        要想将一个对象存储到一个文件中,我们首先需要通过 open 以写入(write) 二进制(binary) 模式打开文件,然后调用 pickle 模块的 dump 函数。这一过程被称作封装(Pickling)。接着,我们通过 pickle 模块的 load 函数接收返回的对象。这个过程被称作拆封(Unpickling) 。
4. Unicode
>>> "hello world"
'hello world'
>>> type("hello world")
<class 'str'>
>>> u"hello world"
'hello world'
>>> type(u"hello world")
<class 'str'>
        当我们阅读或写入某一文件或当我们希望与互联网上的其它计算机通信时,我们需要将我们的 Unicode 字符串转换至一个能够被发送和接收的格式,这个格式叫作“UTF-8”。我们可以在这一格式下进行读取与写入,只需使用一个简单的关键字参数到我们的标准 open 函数中。
# encoding=utf-8
import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()
text = io.open("abc.txt", encoding="utf-8").read()
print(text)        每当我们诸如上面那番使用 Unicode 字面量编写一款程序时,我们必须确保 Python 程序已经被告知我们使用的是 UTF-8,因此我们必须将 # encoding=urf-8 这一注释放置在我们程序的顶端。我们使用 io.open 并提供了“编码(Encoding) ”与“解码(Decoding) ”参数来告诉 Python我们正在使用 Unicode。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: