Python之输入输出

1. print与input

print的基本用法

print()是python的基本输出函数,它有着非常灵活的使用方法,下面通过help()查看print的基本用法,在交互编辑界面输入help(print)

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

可以看到,print的参数为以下几项:

  • value, …要打印的值, 以逗号分隔。
  • sep分隔符,默认以空格分隔(打印的每项之间以空格分开)。
  • end结束符, 默认为换行符(print默认会换行)。
  • file打印的目的对象,默认为标准输出(可以改为其他的类似文件的对象)。
  • flush是否立即输出到file指定的流对象中。

(1) 数据类型
value可以是不同的数据类型,通过逗号将各数据项分开。

>>> print("Hello World!", "2018/11/18", 3.14)
Hello World! 2018/11/18 3.14

(2) 更改分隔符
从上一个例子可以看出,输出的各项以空格进行分隔。更改seq值可以更改分隔符类型,如下:

>>> print("Hello World!", "2018/11/18", 3.14, sep='#')
Hello World!#2018/11/18#3.14

(3) 更改结束符
下面这个例子:

>>> print("Hello World!")
... print("Hello World!")
Hello World!
Hello World!

可以看出,print默认以换行符结束。这里可以通过更改end值更改结束符,如下:

>>> print("Hello World!", end=' ')
... print("Hello World!", end=' ')
Hello World! Hello World!

(4) 更改输出位置
print默认输出到标准输出,我们可以通过file参数来更改输出,如下:

f=open("out.txt", "w")
print("Hello World!", file=f)
f.close()

这里更改输出为out.txt,打开out.txt文件可以看到里面的内容为Hello World!.
值得注意的是,print是不会立即输出到out.txt文件中的,它将要打印的数据保留再缓冲区,当执行到f.close()时才将数据写入文件中。如果需要立即打印到文件中,将flush参数改为true即可。

input的基本用法

同样的,我们先通过help命令查看input的用法,在交互编辑界面输入help(input),得到如下结果:

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

可以看出,input从标准输入读取一个字符串,并去掉最后的换行符。此外,input的prompt参数可同于打印提示信息。注意这里读取的任何内容都会被转换为字符串。

>>> a=input("Input:")
Input:Hello World!
>>> type(a)
<class 'str'>
>>> b=input("Input:")
Input:123
>>> type(b)
<class 'str'>

如果需要读取整数,利用int进行强制转换即可:

>>> c=int(input("Input:"))
Input:123
>>> type(c)
<class 'int'>

小结

1. print可以打印不同的数据类型,且不需要指定数据类型。
2. print输出时各项之间默认以空格分隔,以换行符结尾,可以通过sepend参数更改。
3. print默认输出到标准输出,可通过file参数更改。
4. Input将读取的数据转换为字符串。

2. 文件读写操作

打开关闭文件

打开文件的函数为open(),利用help可查看其用法,由于介绍过长,下面仅贴出一部分:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise IOError upon failure.

从介绍可以看出,open()的作用是打开文件,返回一个流对象,如果失败则抛出错误。参数的意义如下:
[file] 文件对象,文本文件或者是二进制文件。
[mode] 打开模式(读、写、追加、文本文件、二进制文件等),默认为"读文本"。
[encoding] 编码方式,默认值与平台无关。
[errors] 指定编码错误的处理方式。
[newline] 设置换行的方式(None、’\n’、’\r’和’\r\n’)
其中,mode的取值如下:

Character Meaning-
‘r’ 读 (默认)
‘w’
‘x’ 新建文件,写
‘a’ 在文件末尾追加
‘b’ 二进制模式
‘t’ 文本模式(默认)
‘+’ 读写(不单独存在)
‘U’ 通用换行符

可通过上述的组合实现不同的模式,如rb(二进制读)、w+(读写)等。
注意:**利用open()打开文件之后需要用f.close()关闭文件。**也可以使用如下方式打开文件,则不需要手动关闭文件:

with open("data.txt") as f:
	pass

读文件

f.read
f.read用于读取文件中指定字节数的数据,如果不指定字节数,则默认读取文件中所有内容。

with open("data.txt") as f:
    print(f.read())
Line one: Hello World!
Line two: Hello World!
Line three: Hello World!
Line four: Hello World!

f.readline
f.readline用于读取文件中的一行。

with open("data.txt") as f:
    print(f.readline())
Line one: Hello World!

f.readlines
f.readline用于读取文件中所有行。默认返回为所有行构成的list。

with open("data.txt") as f:
    ret = f.readlines()
    print(type(ret))
    print(ret)
<class 'list'>
['Line one: Hello World!\n', 'Line two: Hello World!\n', 'Line three: Hello World!\n', 'Line four: Hello World!']

此外,还可以通过迭代对象来读取所有行。

with open("data.txt") as f:
    for line in f:
        print(line, end='')
Line one: Hello World!
Line two: Hello World!
Line three: Hello World!
Line four: Hello World!

写文件

f.write
f.write用于将字符串写入到文件中,返回写入的字节数。

with open("data.txt", "w") as f:
    print(f.write("Hello World!"))
12

其他文件操作

f.tell
f.tell用于返回文件指针当前的位置(距离文件起始位置的字节数)

with open("data.txt", "r") as f:
    f.read(5)
    print(f.tell())
5

f.seek
f.seek用于移动文件指针到指定的位置。用法如下:

seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
    Change stream position.

    Change the stream position to the given byte offset. The offset is
    interpreted relative to the position indicated by whence.  Values
    for whence are:

    * 0 -- start of stream (the default); offset should be zero or positive
    * 1 -- current stream position; offset may be negative
    * 2 -- end of stream; offset is usually negative

它有两个参数,第一个是偏移量cookie,第二个是起始位置whence。起始位置可以是文件起始位置(0)、当前位置(1), 文件尾(2)。
例子如下:

with open("data.txt", "r") as f:
    f.seek(5)//移动到位置5
    print(f.read())//读取所有内容
 World!

猜你喜欢

转载自blog.csdn.net/weixin_43374723/article/details/84196461