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

        如果希望获取用户的输入内容,并向用户打印出一些返回的结果。我们可以分别通过 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()'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。
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
this is a book about python. it was written by Swaroop C H.its name is "a byte of python". Table of Contents Preface Who This Book Is For History Lesson Status of the book Official Website License Terms Using the interpreter prompt Choosing an Editor Using a Source File Output How It Works Executable Python programs Getting Help Summary 4. The Basics Literal Constants Numbers Strings Variables Identifier Naming Data Types Objects Output How It Works Logical and Physical Lines Indentation Summary 5. Operators and Expressions Introduction Operators Operator Precedence Order of Evaluation Associativity Expressions Using Expressions Summary 6. Control Flow Introduction The if statement ivUsing the if statement How It Works The while statement Using the while statement The for loop Using the for statement Using the break statement The continue statement Using the continue statement Summary 7. Functions Introduction Defining a Function Function Parameters Using Function Parameters Local Variables Using Local Variables Using the global statement Default Argument Values Using Default Argument Values Keyword Arguments Using Keyword Arguments The return statement Using the literal statement DocStrings Using DocStrings Summary 8. Modules Introduction Using the sys module Byte-compiled .pyc files The from..import statement A module's __name__ Using a module's __name__ Making your own Modules Creating your own Modules from..import The dir() function Using the dir function Summary 9. Data Structures Introduction List Quick introduction to Objects and Classes Using Lists Tuple Using Tuples Tuples and the print statement Dictionary Using Dictionaries Sequences Using Sequences References Objects and References More about Strings String Methods Summary 10. Problem Solving - Writing a Python Script The Problem The Solution First Version Second Version Third Version Fourth Version More Refinements The Software Development Process Summary 11. Object-Oriented Programming Introduction The self Classes Creating a Class object Methods Using Object Methds The __init__ method Using the __init__ method Class and Object Variables Using Class and Object Variables Inheritance Using Inheritance Summary 12. Input/Output Files Using file Pickle Pickling and Unpickling Summary 13. Exceptions Errors Try..Except Handling Exceptions Raising Exceptions How To Raise Exceptions Try..Finally Using Finally Summary 14. The Python Standard Library Introduction The sys module Command Line Arguments More sys The os module Summary 15. More Python Special Methods Single Statement Blocks List Comprehension Using List Comprehensions Receiving Tuples and Lists in Functions Lambda Forms Using Lambda Forms The exec and eval statements The assert statement The repr function Summary 16. What Next? Graphical Software Summary of GUI Tools Explore More Summary A. Free/Libré and Open Source Software (FLOSS) B. About Colophon About the Author C. Revision History Timestamp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值