PYTHON 文件读写、坐标寻址、查找替换
读文件
打开文件(文件需要存在)
#打开文件
f = open("data.txt","r") #设置文件对象
print(f)#文件句柄
f.close() #关闭文件
#为了方便,避免忘记close掉这个文件对象,可以用下面这种方式替代
with open('data.txt',"r") as f: #设置文件对象
str = f.read() #可以是随便对文件的操作
完全读取文件
#完全读取文件
f = open("data.txt","r") #设置文件对象
string1 = f.read() #将txt文件的所有内容读入到字符串string1中
f.close() #将文件关闭
print(string1)
按按行读取整个文件方法一(删除回车)
#按行读取整个文件方法一(删除回车)
data = []
f = open("data.txt","r") #设置文件对象
line = f.readline()
if line !='\n' and line[len(line) -1 if len(line)-1>0 else 0] == "\n":#去掉换行符,也可以不去
line_ = line[:-1]
data.append(line_)
while line: #直到读取完文件
line = f.readline() #读取一行文件,包括换行符
if line !='' and line[len(line) -1 if len(line)-1>0 else 0] == "\n":#去掉换行符,也可以不去
line_ = line[:-1]
data.append(line_)
f.close() #关闭文件
print(data)
按行读取整个文件方法一(不删除回车)
#按行读取整个文件方法一(不删除回车)
data = []
f = open("data.txt","r") #设置文件对象
line = f.readline()
data.append(line)
while line: #直到读取完文件
line = f.readline() #读取一行文件,包括换行符
if line !='':
data.append(line)
f.close() #关闭文件
print(data)
按行读取整个文件第二种方法
#按行读取整个文件第二种方法
data = []
for line in open("data.txt","r"): #设置文件对象并读取每一行文件
data.append(line) #将每一行文件加入到list中
print(data )
按行读取整个文件第三种方法
f = open("data.txt","r") #设置文件对象
data = f.readlines() #直接将文件中按行读到list里,效果与方法2一样
f.close() #关闭文件
print(data)
将文件读入numpy数组中
#将文件读入数组中
import numpy as np
data = np.loadtxt("data.txt") #将文件中数据加载到data数组里
print(data)
写文件
列表写入文件
#列表写入文件(直接)
data = ['a','b','c']
#单层列表写入文件
with open("data.txt","w") as f:
f.writelines(data)
#列表写入文件(加入一些东西)
data = ['a','b','c']
#单层列表写入文件
with open("data.txt","w") as f:
for i in data:
f.write(i+'\r\n')
#二维列表写入文件
data =[ ['a','b','c'],['a','b','c'],['a','b','c']]
with open("data.txt","w") as f: #设置文件对象
for i in data:
i = str(i).strip('[').strip(']').replace(',','').replace('\'','').replace(' ',',')+'\r\n' #将其中每一个列表规范化成字符串
print(i)
f.write(i)
#第二种方法,直接将每一项都写入文件
data =[ ['a','b','c'],['a','b','c'],['a','b','c']]
with open("data.txt","w") as f: #设置文件对象
for i in data: #对于双层列表中的数据
f.writelines(i)
#将数组写入文件
import numpy as np
data =[ [1,2,3],[4,5,6],[7,8,9]]
# 第一种方法将数组中数据写入到data.txt文件
np.savetxt("data1.txt",data)
# 第二种方法将数组中数据写入到data.npy文件
np.save("data",data)
import numpy as np
filename = 'data.txt' # txt文件和当前脚本在同一目录下,所以不用写具体路径
dataele_list = []
with open(filename, 'r') as f:
while True:
lines = f.readline() # 整行读取数据
if not lines:
break
dataele_tmp = [float(i) for i in lines.split()] # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
dataele_list.append(dataele_tmp) # 添加新读取的数据
dataele_np = np.array(dataele_list) # 将数据从list类型转换为array类型。
print(dataele_np)
非替换写入
#非替换写入
#r+ 模式的指针默认是在文件的开头
# 如果直接写入,则会覆盖源文件,通过read() 读取文件后,指针会移到文件的末尾,再写入数据就不会有问题了。
# 这里也可以使用a 模式
f2 = open('data.txt','r+')
f2.read()
f2.write('\r\nhello boy!')
f2.close()
#非替换写入
f2 = open('data.txt','a')
f2.write('\r\nhello fff!')
f2.close()
文件坐标插入读取
# 在开始使用open打开文件时候,将打开方式从r,换成rb即可 才可以使用seek移动
f = open('data.txt','rb')
#f.tell() #获取指针位置
print("初始位置",f.tell())
# 开头位置偏离3位置
f.seek(3,0)无锡人流医院 http://www.wxbhnk120.com/
print("开头位置偏离3位置",f.tell())
print("==",f.readline(),"==")
print("读取一行后位置",f.tell())
# 当前位置偏离5位置
f.seek(5,1)
print("当前位置偏离5位置",f.tell())
print("==",f.readline(),"==")
print("读取一行后位置",f.tell())
# 结尾偏离5位置
f = open('data.txt','rb')
f.seek(0,2)
print("结尾偏离0位置",f.tell())
print("==",f.readline(),"==")
print("读取一行后位置",f.tell())
f.seek(3,2)
print("结尾偏离3位置",f.tell())
print("==",f.readline(),"==")
print("读取一行后位置",f.tell())
内容查找
# 内容查找
import re
f = open('data.txt')
source = f.read()
f.close()
r = 'www'
s = len(re.findall(r,source))
print(s)
import re
f = open("data.txt",'r')
count = 0
for s in f.readlines():
li = re.findall("www",s)
if len(li)>0:
count = count + len(li)
print ("Search",count, "www")
f.close()
替换
#替换
f1 = open('data.txt','r')
f2 = open('data2.txt','w')
for s in f1.readlines():
f2.write(s.replace('www','w')+'\r\n')
f1.close()
f2.close()
#排序 去除空行 注释
f = open('data.txt')
result = list()
for line in f.readlines(): # 逐行读取数据
line = line.strip() #去掉每行头尾空白
if not len(line) or line.startswith('#'): # 判断是否是空行或注释行
continue #是的话,跳过不处理
result.append(line) #保存
f.close()
result.sort() #排序结果
print(result)
f = open('data2.txt','w')
for line in result:
f.write(line+'\r\n')
PYTHON 文件读写、坐标寻址、查找替换的更多相关文章
- python文件读写及形式转化和CGI的简单应用
一丶python文件读写学习笔记 open() 将会返回一个 file 对象,基本语法格式如下: open(filename, mode) filename:包含了你要访问的文件名称的字符串值. mo ...
- python 文件读写操作(24)
以前的代码都是直接将数据输出到控制台,实际上我们也可以通过读/写文件的方式读取/输出到磁盘文件中,文件读写简称I/O操作.文件I/O操作一共分为四部分:打开(open)/读取(read)/写入(wri ...
- python文件读写小结
读文件 打开一个文件用open()方法(open()返回一个文件对象,它是可迭代的): >>> f = open('test.txt', 'r') r表示是文本文件,rb是二进制文件 ...
- python文件读写及修改
转载:https://www.cnblogs.com/zhxwind/p/8761618.html 文件的读写有三种形式:读.写和追加. 一.读模式 r 和读写模式 r+ 1.读模式 r 读模式r特点 ...
- Python 文件读写,条件循环(三次登录锁定账号实例)
通过文件读写,条件循环相关语法,实现三次登录失败则锁定该账号的功能 需求一 """需求描述: 1.输入正确账号,密码,退出程序 2.登录失败,重新输入账号密码 3.同一账 ...
- 【学习】python文件读写,用with open as的好处,非常好【转载】
原文链接:http://www.cnblogs.com/ymjyqsx/p/6554817.html 备注:博主还有很多值得学习的笔记,遇到问题可以拜读,非常感谢博主的总结 读写文件是最常见的IO操作 ...
- python文件读写,以后就用with open语句
读写文件是最常见的IO操作.Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘, ...
- Python文件读写(open(),close(),with open() as f...)
Python内置了读写文件的函数,用法和C是兼容的.本节介绍内容大致有:文件的打开/关闭.文件对象.文件的读写等. 本章节仅示例介绍 TXT 类型文档的读写,也就是最基础的文件读写,也需要注意编码问题 ...
- python 文件读写方式
一.普通文件读写方式 1.读取文件信息: with open('/path/to/file', 'r') as f: content = f.read() 2.写入文件中: with open('/U ...
- Python文件读写、StringIO和BytesIO
1 IO的含义 在计算机中,IO是Input/Output的简写,也就是输入和输出. 由于程序和运行时数据是在内存中驻留,由CPU这个超快的计算核心来执行,涉及到数据交换的地方,通常是磁盘.网络等,就 ...
随机推荐
- grpc使用记录(二)简单同步服务实例
目录 1.编写proto文件,定义服务 2.编译proto文件,生成代码 3.编写服务端代码 server.cpp 代码 编译 4.编写客户端代码 client.cpp代码 5.简单测试一下 已经折腾 ...
- nginx https 转发
add_header Content-Security-Policy upgrade-insecure-requests;
- OS X 恢复模式重置 Mac 用户登录密码
关闭你的 Mac.按住 Command + R(⌘R) 组合键,并点按开机按钮,直到出现 标志,进入恢复模式(Recovery Mode)(当然,你也可以先按开机键,在听到启动声后,立即按住 ⌘R ...
- Nginx修改时间戳
1.安装nginx,注意不要安装nginx-common或者nginx-full sudo apt-get install nginx sudo apt-get install nginx-commo ...
- es6 学习小计
es6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这称之为解构:
- Java之输入和输出
输出 在前面的代码中,我们总是用System.out.println()来向屏幕输出一些内容: println是print line的缩写,表示输出并换行.因此,如果输出后不想换行,可以用print( ...
- 如何在jupyter中使用Python2和Python3
首先通过 pip2 install ipython notebook pip3 install ipython notebook 分别安装ipython notebook,安装命令还是推荐使用国内的豆 ...
- 三层交换,单臂路由,vtp
- redis相关文章
redis主从复制相关文章 <redis如何实现主从数据的同步> <一篇文章让你明白Redis主从同步> <redis-sentinel的理解实 ...
- Win10最详细的优化设置 完美解决磁盘100%占用
1.用360优化win10后开不了机的问题原因是禁用了三个服务:在360应用软件服务里dmwappushsvc.diagnsticsTrackingservice.coreMessaging这三个要开 ...