云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

python散装笔记——29: 基本输入和输出

jxf315 2025-01-21 18:45:07 教程文章 21 ℃

1: 使用打印功能

在 Python 3 中,打印功能以函数的形式存在:

print("This string will be displayed in the output")
# This string will be displayed in the output

print("You can print \n escape characters too.")
# You can print escape characters too.

注意:在 Python 2 中使用 from __future__ import print_function 将允许用户使用与 Python 3 代码相同的 print() 函数。这仅在 Python 2.6 及以上版本中可用。

2: 从文件输入

输入也可以从文件中读取。文件可以使用内置函数 open 打开。使用“<命令>>”作为“<名称>>”语法(称为 “上下文管理器”),可以轻松使用 open 并获取文件句柄:

with open('somefile.txt', 'r') as fileobj:
  # write code here using fileobj

这样可以确保代码执行离开代码块时,文件会自动关闭。

文件可以以不同模式打开。在上例中,文件以只读模式打开。如果要以字节形式读取文件,则使用 rb。要向现有文件添加数据,请使用 a。要创建文件或覆盖同名的现有文件,请使用 w。可以使用 r+ 打开一个文件供读写。open() 的第一个参数是文件名,第二个参数是模式。如果模式留空,则默认为 r

# let's create an example file:
with open('shoppinglist.txt', 'w') as fileobj:
  fileobj.write('tomato\npasta\ngarlic')
  
with open('shoppinglist.txt', 'r') as fileobj:
  # this method makes a list where each line
  # of the file is an element in the list
  lines = fileobj.readlines()

print(lines)
# ['tomato\n', 'pasta\n', 'garlic']

with open('shoppinglist.txt', 'r') as fileobj:
  # here we read the whole content into one string:
  content = fileobj.read()
  # get a list of lines, just like int the previous example:
  lines = content.split('\n')

print(lines)
# ['tomato', 'pasta', 'garlic']

如果文件很小,将整个文件内容读入内存是安全的。如果文件非常大,最好逐行或分块读取,并在同一循环中处理输入内容。要做到这一点

with open('shoppinglist.txt', 'r') as fileobj:
  # this method reads line by line:
  lines = []
  for line in fileobj:
    lines.append(line.strip())

读取文件时,请注意操作系统特有的换行符。虽然 fileobj 中的每一行都会自动去掉换行符,但如上图所示,在读取的行上调用 strip() 是安全的做法。

打开的文件(上述示例中的 fileobj)总是指向文件中的特定位置。首次打开时,文件句柄指向文件的最开头,即位置 0:

fileobj = open('shoppinglist.txt', 'r')
pos = fileobj.tell()
print('We are at %u.' % pos) # We are at 0.

读取所有内容后,文件处理程序的位置将指向文件末尾:

content = fileobj.read()
end = fileobj.tell()
print('This file was %u characters long.' % end)
# This file was 19 characters long.
fileobj.close()

文件处理程序的位置可以设置为任何需要的位置:

fileobj = open('shoppinglist.txt', 'r')
fileobj.seek(7)
pos = fileobj.tell()
print('We are at character #%u.' % pos)

您也可以在一次调用中读取文件内容的任意长度。为此,请为 read() 传递一个参数。如果调用 read() 时没有参数,则会一直读到文件的末尾。如果输入参数,则会根据模式(分别为 rbr)读取相应的字节数或字符数:

# reads the next 4 characters
# starting at the current position
next4 = fileobj.read(4)
# what we got?
print(next4) # 'past'
# where we are now?
pos = fileobj.tell()
print('We are at %u.' % pos) # We are at 11, as we was at 7, and read 4 chars.

fileobj.close()

下面的代码将演示字符与字节之间的区别:

with open('shoppinglist.txt', 'r') as fileobj:
  print(type(fileobj.read())) # <class 'str'>
with open('shoppinglist.txt', 'rb') as fileobj:
  print(type(fileobj.read())) # <class 'bytes'>

3: 从 stdin 中读取

Python 程序可以从 unix 管道中读取数据。下面是一个如何从 stdin 读取数据的简单示例:

import sys

for line in sys.stdin:
  print(line)

请注意,sys.stdin 是一个流。这意味着 for 循环只有在流结束时才会终止。

现在,你可以将另一个程序的输出导入你的 python 程序,如下所示:

$ cat myfile | python myprogram.py

在本例中,cat myfile 可以是任何输出到 stdout 的 unix 命令。

另外,使用 fileinput 模块也能派上用场:

import fileinput
for line in fileinput.input():
  process(line)

4: 使用 input()

input 将等待用户输入文本,然后以字符串形式返回结果。

foo = input("Put a message here that asks the user for input: ")

在上例中,foo 将存储用户提供的任何输入。

5: 提示用户输入数字的功能

def input_number(msg, err_msg=None):
  while True:
    try:
      return float(input(msg))
    except ValueError:
      if err_msg is not None:
        print(err_msg)

并且使用它:

user_number = input_number("input a number: ", "that's not a number!")

或者,如果您不想要 “错误信息”,也可以这样做:

user_number = input_number("input a number: ")

6: 打印末尾没有换行符的字符串

在 Python 3.x 中,print 函数有一个可选的 end 参数,即在给定字符串的末尾打印什么。

默认情况下,它是一个换行符,因此相当于这样:

print("Hello, ", end="\n")
print("World!")
# Hello,
# World!

你也可以通过其他字符串来实现行尾打印什么

print("Hello, ", end="")
print("World!")
# Hello, World!

print("Hello, ", end="<br>")
print("World!")
# Hello, <br>World!

print("Hello, ", end="BREAK")
print("World!")
# Hello, BREAKWorld!

如果想对输出进行更多控制,可以使用 sys.stdout.write

import sys

sys.stdout.write("Hello, ")
sys.stdout.write("World!")
# Hello, World!



Tags:

最近发表
标签列表