用python123.io编程世界你好_python语言IO编程

一、文件读写

1、文件的打开和关闭。在python语言中,文件的打开和关闭分别使用的是open函数和close函数,两者一般是配套使用。

open + close模式:需要手动编写关闭文件代码,如果没有手动关闭文件,会引发一系列的问题。

f = open('text.txt',encoding='utf8')

print(f.read())

f.close() #需要手动关闭文件

你好

with + open模式:这种模式下,不需要在手动编写关闭文件的程序代码(f.close()),程序会在执行完with结构体中的程序后自动关闭打开的文件。

with open('text.txt',encoding='utf-8') as f:

print('读取文件信息:',f.read())

print('再次尝试读取文件:',f.read()) #文件已经被关闭,读取失败

读取文件信息: 你好

---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

in

2 print('读取文件信息:',f.read())

3

----> 4 print('再次尝试读取文件:',f.read())

ValueError: I/O operation on closed file.

2、open方法调用语法:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数:

file:必填,文件路劲(相对路径或者绝对路径)

mode:可选,文件打开模式

buffering:设置缓冲

encoding:一般设置为‘utf8’

errors:报错级别

newline:区分换行符

closefd:传入的file参数类型

opener:可选

文件打开模式mode:

方法

含义

解释

r

read

读取(默认)

w

write

截断写入

a

append

在原内容后追加写入

x

exclusive

独占写入,文件存在会报错

b

binary

二进制模式

t

text

文本模式(默认)

+

扩展

扩展为读写模式

mode='rt'模式:这是文件打开默认模式,比如:

with open('text.txt',encoding='utf-8') as f:

print('读取文件信息:',f.read())

读取文件信息: 你好

上例等效于:

with open('text.txt',mode='rt',encoding='utf-8') as f:

print('读取文件信息:',f.read())

读取文件信息: 你好

mode='w'模式:它会将覆盖掉原来的数据,所以使用时需要小心。比如:

with open('text.txt',mode='w',encoding='utf-8') as f:

f.write('hello world!')

with open('text.txt',mode='rt',encoding='utf-8') as f:

print('读取文件信息:',f.read())

读取文件信息: hello world!

上例,原文件信息为“你好”,但在“截断写入w”模式下写入下,文件中保存到信息被覆盖,现在文件信息为:hello world!所以使用“截断写入w”模式时需要非常小心。

mode='a'模式:追加模式,它会保留原来文件信息,并在文件末尾追加新的信息。

with open('text.txt',mode='a',encoding='utf-8') as f:

f.write('这是追加的内容')

with open('text.txt',mode='rt',encoding='utf-8') as f:

print('读取文件信息:',f.read())

读取文件信息: hello world!这是追加的内容

mode='x'模式:它会创建一个新文件,并写入内容,如果文件存在会报错。

with open('text.txt',mode='x',encoding='utf-8') as f:

f.write('这是独占写入模式')

---------------------------------------------------------------------------

FileExistsError Traceback (most recent call last)

in

----> 1 with open('text.txt',mode='x',encoding='utf-8') as f:

2 f.write('这是独占写入模式')

FileExistsError: [Errno 17] File exists: 'text.txt'

错误提示,文件已经存在了。

3、读写方法

方法

作用

read([size])

读取指定字节的内容

readline([size])

读取一行内容

readlines([size])

读取多行内容,返回列表

write(s)

写入字符串

writelines(s)

写入数据,支持字符串也支持列表

tell()

获取当前文件位置

seek(n)

移动文件位置

close()

关闭文件

read方法:读取指定字节的内容,显示的是字符串。

with open('text.txt',mode='r',encoding='utf-8') as f:

print(type(f.read()))

f.seek(0)#文件指针回到初始位置

print("读取到的内容为:",f.read())

读取到的内容为: hello world!这是追加的内容

123

456

789

readlines方法:读取多行内容,返回的是列表。

with open('text.txt',mode='r',encoding='utf-8') as f:

print(type(f.readlines()))

f.seek(0)#文件指针回到初始位置

print("读取到的内容为:",f.readlines())

读取到的内容为: ['hello world!这是追加的内容\n', '123\n', '456\n', '789']

readline方法:读取一行内容。

with open('text.txt',mode='r',encoding='utf-8') as f:

print(type(f.readline()))

f.seek(0)#文件指针回到初始位置

print("读取到的内容为:",f.readline())

读取到的内容为: hello world!这是追加的内容

writelines方法:将列表写入。

with open('text.txt',mode='a+',encoding='utf-8') as f:

f.writelines(['123','你好'])

f.seek(0)

print(f.read())

hello world!这是追加的内容

123

456

789123123123123123123123你好

write方法:将字符串写入,注意写的是字符串。

with open('text.txt',mode='a+',encoding='utf-8') as f:

f.write(['123','你好'])

f.seek(0)

print(f.read())

TypeError: write() argument must be str, not list

tell方法:获取当前文件位置。

with open('text.txt',mode='r',encoding='utf-8') as f:

print("读取到的内容为:",f.readline())

print("当前指针位置为:",f.tell())

print("读取到的内容为:",f.readline())

print("当前指针位置为:",f.tell())

读取到的内容为: key1kye2

当前指针位置为: 9

读取到的内容为: hello world!这是追加的内容

当前指针位置为: 43

二、输入和输出

1、input函数

input()函数有且只有一个参数,在执行input() 函数时会暂停程序运行,同时等待键盘输入;直到回车被按下,函数的参数即为提示输入的类型永远是字符串型(str)。这里尤其需要注意。

a = input() #输入1

print(type(a))

1

如果没有注意input函数输入的类型是字符串,那可能会导致如下错误,比如在进行数字计算时。

a = input() #输入1

b = input() #输入2

print(a + b)#按理说应该是1 + 2 = 3,但结果显示的是12,这其实是字符串的拼接导致。

1

2

12

2、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.

参数:

value:是带输出的内容。

sep:内容的分隔符。

end:内容结尾符号。

file:一个file-like对象,被输出的流。

flush:是否强制刷新。

sep参数:内容的分隔符,默认情况下是空格’‘进行分割。

print(1,2,"hello",(1,2,3))

1 2 hello (1, 2, 3)

上例是默认情况下空格分隔,再看’-‘分割:

print(1,2,"hello",(1,2,3),sep='-')

1-2-hello-(1, 2, 3)

end参数:内容结尾符号,默认情况下是换行符’\n‘。

print(1,2,"hello",(1,2,3))

print(1,2,"hello",(1,2,3))

1 2 hello (1, 2, 3)

1 2 hello (1, 2, 3)

输出的内容自动换行了,若把默认换行符修改成空格,那么就显示在一行:

print(1,2,"hello",(1,2,3),end='')

print(1,2,"hello",(1,2,3))

1 2 hello (1, 2, 3)1 2 hello (1, 2, 3)

还可以任意修改,比如结尾是三个???:

print(1,2,"hello",(1,2,3),end='???')

1 2 hello (1, 2, 3)???

file参数:一个file-like对象,被输出的流,默认情况下值是sys.stdout,其实就是把想要输出的内容显示的解释器控制台。

要理解sys.stdout,我们需要知道标准流的概念。背景如下(维基百科)

在Unix之前的操作系统,程序必须明确指出链接到合适的输入和输出数据。对这当中的许多系统而言,这牵涉一些错综复杂而又与特定操作系统相关的事,是一件吓人的程序设计挑战。如控制环境设置、访问一个文件表格、决定区域数据集、和决定读卡器、磁带、磁盘、打印机、打卡机或交互式终端机。

Unix 提供许多开创产的进步,其中之一是提供 抽象设备 :它免除了程序须要知道或在意它正与哪个设备沟通。 Unix 借由数据流的概念来消除这种复杂:一种数据字节的有序序列,直到读到文件结尾。程序员亦可依需求写入而无须宣告写入多少或如何组织。

另一个 Unix 突破为默认自动链接输入和输出-程序(和程序员)不用为了典型输入-处理-输出程序创建输入和输出。相对地,之前操作系统通常要求一些-有时复杂-工作控制语言(Job Control Language)以创建链接,或者,相者近似于协调的责任。

既然 Unix 提供标准流,Unix C 的运行环境被要求要支持它。结果不管什么操作系统, C 的运行环境(及 C 的派生)都提供类似功能。

python 中有三种标准输入输出流:sys.stdin(标准输入)、sys.stdout(标准输出)、sys.error(标准错误)

重定向

python中将标准输出重定向到某个文件当中:

with open('text.txt',mode='w',encoding='utf8') as f:

print("这是我要输出的内容",file=f)

结果没有显示,然后打开'text.txt'后,可以查看到输出的信息。

输入重定向到python程序当中,比如有这样一个程序:test.py

while True:

text = input()

print(text)

有这样一个文本文件(txt.txt),信息如下:

hello world!

hello

123

456

在cmd命令环境下执行python语句(python test.py < txt),输入重定向到python程序当中:

E:\python\WordCloudPro\mytest>python test.py < txt

hello world!

hello

123

456

Traceback (most recent call last):

File "test.py", line 5, in

text = input()

EOFError: EOF when reading a line

attempt to call a nil value

程序将文本文件(txt.txt)中的信息重定向到python程序中。

还可以在cmd命令环境下,把python程序中的输出信息和错误信息分别重定向到不同文件中:

python test.py 1>1.txt 2>error.txt

把输出信息定向到1.txt文件中,把错误信息重定向到error.txt文件中。

还可以在cmd命令环境下,把python程序中的输出信息重定向到某个文件中:

python test.py 1>1.txt 2>&1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值