IO

io_input.py

# 用户输入输出

# 通过切片将序列里的内容转置的tip
def reverse(text):
    return text[::-1]
    
# 判断是不是回文   
def is_palindrome(text):
    text = preprocess(text)
    return text == reverse(text)

# 忽略文本的空格、标点和大小写
def preprocess(text):
    # 都变成小写
    text = text.lower()
    
    # 删掉空格
    # strip() "   xyz   "  -->  "xyz"
    # lstrip() "   xyz   "  -->  "xyz   "
    # rstrip() "   xyz   "  -->  "   xyz"
    # replace(' ','')  "   x y z   "  -->  "xyz"
    text = text.replace(' ','')
    
    # 删掉英文标点符号
    # 需要导入string里的punctuation属性
    import string
    for char in string.punctuation:
        # 为什么这里一定要用自身去替换
        # text1 = text.replace(char,'')
        text = text.replace(char,'')
    return text
    
something = input("Enter text: ")

if is_palindrome(something):
    print('Yes, it is a palindrome.')
else:
    print('No, it is not a palindrome')

io_using_file.py

# 文件读写

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
'''

# 'r'阅读 'w'写入 'a'追加
# 't' 文本模式  'b'二进制模式

# 打开文件以编辑('w')
f = open('poem.txt','w')

# 向文件中编写文本
f.write(poem)

# 关闭文件
f.close()
    
# 如果没有特别指定,将假定启用默认的'r'模式
f = open('poem.txt')
while True:
    # readline() 读取文件的每一行还包括了行末尾的换行符
    line = f.readline()
    # 长度为零指示 EOF
    # 当返回一个空字符串时,表示我们已经到了文件末尾要退出循环
    if len(line) == 0:
        break
    # 每行line的末尾都有换行符因为他们是从一个文件中进行读取的
    print(line,end='')

# 关闭文件
f.close()

io_pickle.py

# Python中提供了一个Pickle Module
# 它可以将Python对象存储到一个文件中 这样可以 持久地Persistently存储对象
# dump 与 load

import pickle

# 存储对象的文件名
shoplistfile = 'shoplist.data'

# list里的东西
shoplist = ['apple','mango','carrot']

# 写到文件里
f = open(shoplistfile,'wb') #以二进制模式写入

# Dump the object to a file     (Pickling)
pickle.dump(shoplist,f)
f.close()

# 销毁shoplist变量
del shoplist

# 从文件再次读入
f = open(shoplistfile,'rb')

# Load the object from the file     (Unpickling)
storedlist = pickle.load(f)

print(storedlist)

io_unicode.py

import io

f = io.open('abc.txt','wt',encoding='utf-8')
f.write(u'我是一个中国人')
f.close()

text = io.open('abc.txt',encoding='utf-8').read()
print(text)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • IO编程概念 IO在计算机中指Input/Output,也就是输入和输出。由于程序和运行时数据是在内存中驻留,由C...
    时间之友阅读 732评论 0 0
  • IO在计算机中是指input/output,也就是输入和输出。由于程序和运行时数据是在内存中驻留,由CPU这个超快...
    Sun_atom阅读 1,729评论 0 0
  • 本文是笔者学习廖雪峰Python3教程的笔记,在此感谢廖老师的教程让我们这些初学者能够一步一步的进行下去.如果读者...
    相关函数阅读 1,496评论 2 9
  • 文件读写 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。由于文件读写时都有可能产...
    时间之友阅读 477评论 0 0
  • 从全文结构来看,多以“风雨。。。”为重章叠句内容,风雨代表着什么?仅仅是内心的波澜起伏?风雨总会伴着鸡鸣的出现,每...
    慕言1104阅读 371评论 1 2