[Python学习]Python中文件内容读取操作

文件:pi_digits.txt

3.1415926535

  8979323846

  2643383279

————————————————————

#-*- coding:utf-8 -*-

#Python读取文件内容

with open('pi_digits.txt') as file_object:

    contents = file_object.read()

    print(contents.rstrip())

#读取文件路径设置,Windows中使用\反斜杠路径单引号前加r,代表不要转义

with open(r'data/filename.txt') as file_object:

    contents = file_object.read()

    print(contents.rstrip())

#逐行读取文件内容,rstrip()方法去除空行

filename = 'pi_digits.txt'

with open(filename) as file_object:

    for line in file_object:

        print(line.rstrip())

#读取文件每行内容,为列表

with open(filename) as file_object:

    lines = file_object.readlines()


for line in lines:

    print(line.rstrip())


#使用读取的文件内容

pi_string = ''

for line in lines:

    pi_string += line.strip()

print(pi_string)

print(len(pi_string))

#查找文件内容中,是否包含关键字符

findstr = input("Enter str, in the from contents: ")

if findstr in pi_string:

    print(findstr + " exist!")

else:

    print(findstr + " does not exist!")

你可能感兴趣的:([Python学习]Python中文件内容读取操作)