python基础-文件和异常
从文件中读取数据
比如,与执行文件在同一目录下:
with open('demo_2.txt') as file_object:
content = file_object.read()
print(content)
就可以将txt中的内容全部读取出来。
关键字with再不需要访问文件后就将其关闭。让py处理打开和关闭文件的逻辑,不要手动打开关闭,可能会产生bug。
read()在文末会返回一个空字符串,最终展示出来的就是一个空行,如果要去掉这个空字符串:
with open('demo_2.txt') as file_object:
content = file_object.read()
content = content.rstrip()
print(content)
rstrip()删除字符串末尾的空白。
如果要读取的文件不根py程序脚本在同一个目录的时候,可以使用相对路径或者绝对路径。
注意:win系统中是\,而Linux等其他系统中是/
filepath = r'D:\python-work\demo_2.txt'
with open(filepath) as file_object:
使用绝对路径,可以读取系统任何地方的文件。
注意:反斜杠\在py中被视为转义标记,为确保在win上万无一失,应以原始字符串的方式指定路径,即在字符串单引号之前加上r。
逐行读取
filepath = r'D:\python-work\demo_2.txt'
with open(filepath) as file_object:
for line in file_object:
print(line)
通过对文件对象循环,遍历文件中的每一行。但是这样遍历会发现空白行更多了。
为何会出现这些空行?因为在文件中,每行的末尾都有一个看不见的换行符,而print语句也会加上一个换行符,因此这样一来每行末尾就会有两个换行符,一个来自文件一个来自print语句。如果要清除多余的空白行,还是使用rstrip()
filepath = r'D:\python-work\demo_2.txt'
with open(filepath) as file_object:
for line in file_object:
print(line.rstrip())
这样修改之后,就只有print语句的换行符了。
文件内容转换为列表
使用with时,open返回的对象只能在with代码块中可用。如果要在with代码块之外使用,那么可以将各行存于列表中,并在with外部使用这个列表。
filepath = r'D:\python-work\demo_2.txt'
with open(filepath) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rsplit())
拼接所有行到一个字符串中:
filepath = r'D:\python-work\demo_2.txt'
with open(filepath) as file_object:
lines = file_object.readlines()
pistr = ''
for line in lines:
pistr += line.strip()
print(pistr)
strip()删除位于每行左边的空格,rstrip是删除每行右边的空格。
py读取文件内容获取的是字符串类型,如果要转换为数字则使用int(),浮点数float()
对于可处理的数据量,py没有限制,只要内存足够大。
如果要对pistr只取前面的52个字符:
print(pistr[:52] + '...')
检测某个字符是否在字符串中
search_str = 'switch1'
long_str = 'I like switch very much!'
if search_str in long_str:
print('good')
else:
print('no!')
检测到字符串后,进行替换replace
search_str = 'switch'
long_str = 'I like switch very much!'
if search_str in long_str:
print('good')
# 将switch替换为其他文字
long_str = long_str.replace('switch', '替换后的字符串')
print(long_str)
else:
print('no!')
最终输出
good
I like 替换后的字符串 very much!