python中操作文件的实践(2)

上一篇我总结了python对于文件操作的一些常用方法,这一篇主要记录对文件操作的一些常用方法

1.将文件中的内容进行替换
复制代码
import os
with open('python1.txt',encoding='utf-8') as f1,\
    open('python1_bak.txt',encoding='utf-8',mode='w') as f2:
    for line in f1:
        new_line=line.replace('abc','哈喽')
        f2.write(new_line)
os.remove('python1.txt')
os.rename('python1_bak.txt','python1.txt')
2.Python读取文件忽略文件中空行
复制代码
#isspace()详解
mystr = 'helloworld'
print(mystr.isspace())
#输出结果
False
mystr = 'hello world'
print(mystr.isspace())
#输出结果
False
mystr = ''
print(mystr.isspace())
#输出结果
False
mystr = ' '
print(mystr.isspace())
#输出结果
True
mystr = '      '
print(mystr.isspace())
#输出结果
True

with open('python1.txt', "r", encoding="UTF-8") as r:
    for line in r:
        if line.isspace():  #如果是空行就忽略
            pass
        else:
            print(line)  #如果不是空行就打印出来
3.如何在Python中一次读取N行文件
复制代码
with open('python1.txt', "r", encoding="UTF-8") as r:
    lines=r.readlines()
    print(lines)
    for line in lines[:5]:
        print(line.strip())
4.读写csv文件。

(1)csv文件的写入

复制代码
import csv
with open('test.csv1','w') as f1:
    writer = csv.writer(f1)
    writer.writerow(['name', 'age', 'score'])

(2)csv文件的读取

复制代码
import csv
with open('test.csv','r') as f1:
    reader=csv.reader(f1)
    for row in reader:
        print(row)
5.将数据写入内存

(1)StringIO:将字符串数据写入到内存里面

复制代码
from io import StringIO  
  
# 创建一个StringIO对象  
f = StringIO()  
# 可以像操作文件一下,将字符串写入到内存中  
f.write('hello\r\n')  
f.write('good')  
  
# 使用文件的 readline和readlines方法,无法读取到数据  
# print(f.readline())  
# print(f.readlines())  
  
# 需要调用getvalue()方法才能获取到写入到内存中的数据  
print(f.getvalue())  
  
f.close()  

(2)BytesIO**:**二进制数据写入到内存里

复制代码
from io import BytesIO  
  
f = BytesIO()  
f.write('你好\r\n'.encode('utf-8'))  
f.write('中国'.encode('utf-8'))  
  
print(f.getvalue())  
f.close()  
相关推荐
FriendshipT17 小时前
Ultralytics:解读 YOLO26 知识蒸馏
人工智能·pytorch·python·深度学习·yolo
BUG研究员_17 小时前
工具绑定与调用
python·agent
苏灿烤鱼17 小时前
AI Agent 深拆 | 图能让 AI 决策可追责吗?Semantica 登顶拆解
python·github·agent
Sirius.z1 天前
第R6周:LSTM实现糖尿病探索与预测
python
名字还没想好☜1 天前
Python f-string 进阶:数字格式化、对齐填充、调试 = 号与嵌套表达式
开发语言·数据库·python·字符串格式化·f-string
·薯条大王1 天前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
Dxy12393102161 天前
Python 如何使用 MySQL 的事务
python·mysql
今儿敲了吗1 天前
Python ——第三方包
笔记·python
麒麟水手1 天前
国产银河麒麟系统开发实录:跑通Streamlit,我踩过的6个坑
python
麒麟水手1 天前
麒麟系统部署检查清单:上线前30分钟,逐项自查这4类问题
python