python文件读写之基本语法

使用python中的open()及其参数,写入及读取文件
摘要由CSDN通过智能技术生成

python文件读写之基本语法

简单的文件读取
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date    : 2020-11-11 16:11:58
# @Author  : EricRay
# @Email   : ericray.tech@outlook.com
# @Link    : https://blog.csdn.net/ericleiy/
# @Description: 文件读取


with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())    # rstrip()删除字符串末尾的空白

# Windows使用绝对路径
# file_path = 'C:\Users\other_files\text_file\filename_txt'
# with open(file_path) as file_object:


# 逐行读取
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    for line in file_object:
        print(line)
        # print(line.rstrip())


# 使用文件内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()  # 创建一个包含文件各行内,列表

pi_string = ''
for line in lines:
    pi_string += line.strip()

print(pi_string)
print(len(pi_string))
"""
Python读取所有文本都解读为字符串。使用数字要用int()或者float()进行转换
"""

"""
w写入文件;r读取模式; a附加模式;r+读取和写入;默认只读模式
"""
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love you so much!\n")
    file_object.write("I love myself only!\n")

with open(filename, 'a') as file_object:
    file_object.write("I emmmm ,So...\n")

简单的写入:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2020-11-12 14:35:37
# @Author  : EricRay
# @Email   : ericray.tech@outlook.com
# @Link    : https://blog.csdn.net/ericleiy/
# @Description 将输入的用户名写入guest.txt文件中

guest_file = 'guest.txt'
with open(guest_file, 'a') as file_object:
    prompt = "\nPlease write your name, and enter 'quit' to end,thanks:\n"
    message = ""
    while message != 'quit':
        message = input(prompt)
        if message != 'quit':
            message = message.title() + ", Welcome, and have a good day!"
            # print(message)
            file_object.write(message + "\n")

更多python文件操作问题参考:python文件操作异常处理

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值