Python基础5(文件操作)

Python基础— 文件

1.读取文件

with open('pi_digits.txt') as file_object:
    '''到当前目录中查找文件'''
    contents = file_object.read()
    print(contents)
   #read()到达文件末尾时返回一个空字符串,打印出来多一空行,要删除多余的空行,使用rstrip()
   # print(contents.rstrip())

'''相对路径下'''
with open('text_files\pi_digits.txt') as file_object:
    contents=file_object.read()
    print(contents)

'''绝对路径下'''
file_path='H:\pythonpj\\text_files\pi_digits.txt'
with open(file_path) as file_object:
    contents=file_object.read()
    print(contents)


'''逐行读取'''
file_name='pi_digits.txt'

''''''
with open(file_name) as file_object:
    for line in file_object:
        print(line)          #逐行打印会每行多一空行

with open(file_name) as file_object:
    for line in file_object:
        print(line.rstrip()) #逐行打印消去空行


#创建一个包含文件各行内容的列表
#readlines() 从文件中读取每一行,并将其存储在一个列表中
filename='pi_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()

for line in lines:
    print(line.strip())

'''处理FileNotFoundError异常

'''

f_name='a.txt'
try:
    with open(f_name) as f_obj:   # file_object 可以简写成 f_obj
        contents=f_obj.read()
except FileNotFoundError:
    msg = "Sorry ,the file " + f_name + " does not exit."
    print(msg)

2.使用文件的内容

'''使用文件的内容'''

filename='pi_digits.txt'
with open(filename) as file_object:
    lines=file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.rstrip()   #rstrip() 可删除每行末尾的换行符

print(pi_string)
print(len(pi_string))

pi_string2=''

for line in lines:
    pi_string2 += line.strip()    #strip() 删除所有的空格

print(pi_string2)
print(len(pi_string2))

print(pi_string2[:22]+'...')     #输出小数点后20位

#检查输入的字符串是否包含在文件中
birthday=input("Enter your birthday: ")
if birthday in pi_string2:
    print("yes!")
else:
    print("no!")

3.写入文件

#写入空文件

filename='programming.txt'

'''open(filename,'w'/'r'/'a')提供两个实参,第一个是打开文件的名称,第二个系统默认是只读模式打开文件
    若以‘w’模式打开时,如果指定的文件已经存在,python将在返回文件对象前清空该文件
    'a'方式给文件添加内容,不是覆盖原有的内容
'''

with open(filename,'w') as file_object:
    file_object.write("I love programming~")
    file_object.write("I love creating new games")
    '''write()不会在写入的文本末尾添加换行符'''
    file_object.write("I love python\n")
    file_object.write("I love java")
"""I love programming~I love creating new gamesI love python
    I love java
"""
'''
with open(filename) as file_object:
    print(file_object.read())
'''

with open(filename,'a') as file_object:
    file_object.write("I also love C++\n")
    file_object.write("Go\n")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值