Python学习----文件读取

# -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 16:00:57 2019

@author: cc
"""
#文件操作

'''打开当前目录下文件'''
#with会在不需要访问文件后将其关闭,避免使用close()关闭
#rstrip()函数用于删除多余的换行符
with open('digits.txt') as file_object:
    contents=file_object.read()
    print(contents.rstrip())
print('\n')

'''使用相对路径访问文件'''
#.\表示上级目录
with open('.\digits.txt')as file_object:
    contents=file_object.read()
    print(contents.rstrip())
print('\n')
    
'''使用绝对路径读取文件'''
file_path='G:\python学习\digits.txt'
with open(file_path) as file_object:
    contents=file_object.read()
    print(contents.rstrip())
print('\n')

'''逐行读取'''
filename='digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
print('\n')


'''创建包含文件内容的列表'''
#readlines()创建列表
#strip()删除空格
filename='digits.txt'
digits=[]
with open(filename) as file_object:
    digits=file_object.readlines()
pi_string=''
for line in digits:
    #pi_string += line.rstrip()
    pi_string += line.strip()
print(pi_string)
print(float(pi_string))
print(len(pi_string))

'''exercise'''
#全部读取
filename='learning_python.txt'

with open(filename) as file_object:
    contents=file_object.read()
print(contents)
print('\n')


#按行读取
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
print('\n')

#读取成列表
with open(filename) as file_object:
    lines=file_object.readlines()
    '''拼接成一行字符'''
lines_string=''
for line in lines:
    lines_string+=line.strip()
print(lines_string)
print('\n')
#replace()函数能够临时替换指定字符,但不会真正改变字符串
print(lines_string.replace('python','c'))
print('\n')
print(lines_string)

运行结果:

runfile('G:/python学习/file_operation.py', wdir='G:/python学习')
3.1414926535
  8979323846
  2643383279


3.1414926535
  8979323846
  2643383279


3.1414926535
  8979323846
  2643383279


3.1414926535
  8979323846
  2643383279


3.141492653589793238462643383279
3.1414926535897933
32
In python you can learn many intresting things!
In python you can creative a magic world!
In python you can gain knowleges!


In python you can learn many intresting things!
In python you can creative a magic world!
In python you can gain knowleges!


In python you can learn many intresting things!In python you can creative a magic world!In python you can gain knowleges!


In c you can learn many intresting things!In c you can creative a magic world!In c you can gain knowleges!


In python you can learn many intresting things!In python you can creative a magic world!In python you can gain knowleges!

你可能感兴趣的:(Python学习)