lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

    • Python 基础

      • 数据结构
      • 函数
      • 异常
      • 控制语句
      • 运算符
      • 模块
      • 输入输出
        • 输入输出
      • json
    • Python 数据库

    • 面向对象

    • Python Web

    • Python 进阶

  • leetcode

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • python
  • 基础
2023-05-04
目录

输入输出

# 输入输出

# 输入

## 回文测试
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")
  1. [::-1], 倒序反转字符串

# 文件写

poem ="""
    早发白帝城
     唐 李白
朝辞白帝彩云间,千里江陵一日还。
两岸猿声啼不住,轻舟已过万重山。 
"""
f = open('poem.txt', 'w',encoding='utf-8')

f.write(poem)
f.close()
  1. f = open('poem.txt', 'w',encoding='utf-8'), 文件写
  2. f.write(poem), 文件写入内容

# 文件输出

f = open('poem.txt', 'r', encoding='utf-8')

while True:
    line = f.readline()
    ## 文件结束
    if len(line) == 0:
        break
    ## readline 已经有换行符
    print(line, end='')

f.close()
  1. f = open('poem.txt', 'r', encoding='utf-8'), 文件读
  2. line = f.readline(), 文件一行行读

# with

with open('poem.txt', 'r', encoding='utf-8') as f:
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line.strip())
  1. with open('poem.txt', 'r', encoding='utf-8') as f:, 语法糖写法, 可不容易出错

# StringIO

在内存中读写Str

# 读

from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
  1. f = StringIO(), f.write(str), 像文件一样写入str
  2. f.getvalue(), 获得写入的str

# 写

from io import StringIO
f1 = StringIO('Hello!\nHi\nGoodbye!\n')
while True:
    s = f1.readline()
    if s == '':
        break
    print(s.strip())
  1. f1 = StringIO('Hello!\nHi\nGoodbye!\n'),用一个str 初始化 StringIO,
  2. s = f1.readline(),像文件一样读取

# 持久化

import pickle

shoplistfile = 'shoplist.data'

shoplist  = ['apple', 'mango', 'carrot']

f = open(shoplistfile, 'wb')
## 转储对象至文件
pickle.dump(shoplist, f)

f.close()

f = open(shoplistfile, 'rb')
## 从文件中载入对象
storeList = pickle.load(f)

print(storeList)

模块
json

← 模块 json→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式