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文件操作异常处理