python中文件的读取与写入以及os模块

1.文件读取的三部曲:打开 ---> 操作 ----> 关闭

r(默认参数):
-只能读,不能写
-读取文件不存在 会报错
FileNotFoundError: [Errno 2] No such file or directory: ‘/tmp/westos‘

w(写)
-write only
-文件不存在的时候,会自动创建新的文件
-文件存在的时候,会清空文件内容并写入新的内容

a(追加):
-write only
-写:不会清空文件的内容,会在文件末尾追加
-写:文件不存在,不会报错,会创建新的文件并写入内容
r+
-r/w
-文件不存在,报错
-默认情况下,从文件指针所在位置开始写入

w+
-r/w
-文件不存在,不报错
-会清空文件内容

a+
-r/w
-文件不存在,不报错
-不会清空文件,在末尾追加   

f = open(‘/tmp/westos3‘,‘w+‘) /tmp/westos3文件不存在,自动创建了文件并写入了信息

print(f)
print(f.tell()) 打印文件指针的位置 此时为0
f.write(‘111‘) 写入‘111’
print(f.tell()) 再次打印指针位置可以看到指针为3
f.close() 关闭文件

f = open(‘/tmp/redhat‘,‘a+‘) 不会清空文件,在末尾追加
print(f) 文件指针的位置开始为0
print(f.tell())
f.write(‘111‘) 文件执行5此后指针在15
print(f.tell())
f.close() 关闭文件

2.文件的操作

#1.打开文件
f = open(‘/tmp/westos‘,‘r‘)
#2.操作
print(f)
#读文件
#content = f.read()
#print(content)

#写文件
#告诉当前的文件指针所在的位置
#print(f.tell())
#f.write(‘westos‘)
#print(f.tell())
#f.write(‘redhat‘)
#print(f.tell())

#判断文件对象拥有的权限
print(f.readable()) 是否可读
print(f.writable()) 是否可写
print(f.tell()) 文件的指针
content = f.read() 把读取的内容指向content
print(content)
print(f.tell())
content1 = f.read()
print(content1)
#print(content)

3.关闭文件
f.close()

2.如果读取是 图片 音频 视频(非纯文本文件)
需要通过二进制的方式读取和写入
-读取纯文本
r r+ w w+ a a+ == rt rt+ wt wt+ at at+
-读取二进制文件
rb rb+ wb wb+ ab ab+

#读取二进制文件内容
f1 = open(‘hello.png‘,mode=‘rb‘) 只读模式
content = f1.read()
f1.close()

#写入要复制的文件的内容
f2 = open(‘lucky.jpg‘,mode=‘wb‘) 写入模式
f2.write(content)
f2.close()

复制hello.png并创建新的lucky.jpg

3.
默认情况下读取文件的内容 小的文件:直接用read读取即可
如果是一个大文件(文件大小>=内存大小) readline()
f = open(‘/tmp/passwd‘,‘rb+‘)
#按行读取
#print(f.readline())

#按字节读取
#print(f.read(3))
#读取文件内容,并返回一个列表,列表元素分别为文件的行内容
print(f.readlines())
#指针的移动
#print(f.tell())
#print(f.read(10))
#print(f.tell())
#f.seek(2,2)

seek:指针移动
第一个参数:偏移量 >0:代表向后移动 <0 代表向前移动
第二个参数:
0:移动指针到文件开头
1:当前位置
2:移动指针到末尾

#读取/tmp/passwd内容,返回一个列表,去掉后面的\n

f = open(‘/tmp/passwd‘)
print(list(map(lambda x:x.strip(),f.readlines())))
print([line.strip() for line in f.readlines()])
f.close()

#创建文件data.txt 文件共100000行,
#每行存放以一个1~100之间的整数

import random

f = open(‘data.txt‘,‘a+‘)
for i in range(100000):
f.write(str(random.randint(1,100)) + ‘\n‘)
#移动文件指针
f.seek(0,0)
print(f.read())
f.close()

4.
上下文管理器:打开文件,执行完with语句内容之后,自动关闭文件
with open(‘/tmp/passwd‘) as f:
print(f.read())

#将第一个文件的内容写道第二个文件中
with open(‘date.txt‘) as f1,open(‘data3.txt‘,‘w+‘) as f2:
f2.write(f1.read())
f2.seek(0,0)
print(f2.read())

练习:
生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B

01-AF-3B-xx-xx-xx
-xx
01-AF-3B-xx
-xx
01-AF-3B-xx-xx
-xx
01-AF-3B-xx-xx-xx

import string
import random

def create_mac():
MAC = ‘01-AF-3B‘
#生成16进制的数
hex_num = string.hexdigits
for i in range(3):

从16进制字符串中随即选出两个数字来

    #返回值是列表
    n = random.sample(hex_num, 2)
    #拼接列表中的内容,将小写的字母转换成大写的字母
    sn = ‘-‘ + ‘‘.join(n).upper()
    MAC += sn
return MAC

#主函数:随即生成100个MAC地址
def main():

以写的方式打开一个文件

with open(‘mac.txt‘, ‘w‘) as f:
    for i in range(100):
        mac = create_mac()
        print(mac)
        #每生成一个MAC地址,存入文件
        f.write(mac + ‘\n‘)

main()

#1. 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
#2. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;

import random

def create_ip_file(filename):
ips = [‘172.25.254.‘ + str(i) for i in range(0,255)]
print(ips)
with open(filename,‘a+‘) as f:
for count in range(1200):
f.write(random.sample(ips,1)[0] + ‘\n‘)

#create_ip_file(‘ips.txt‘)

def sorted_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f:
for ip in f:
if ip in ips_dict:
ips_dict[ip] += 1
else:
ips_dict[ip] = 1
sorted_ip = sorted(ips_dict.items(),
key= lambda x:x[1],reverse=True)[:count]
return sorted_ip
print(sorted_ip(‘ips.txt‘,20))

import random
f = open(‘/tmp/isp1.txt‘,‘w+‘) #以w+模式打开创建文件
for i in range(1200):
ip = ‘172.25.254.‘
num = random.randint(0,255) #拼接172.25.254.(num)
f.write(ip+str(num)+‘\n‘)
f.seek(0,0) #从指针最开始读取
s = {}
for i in f.readlines():
if i not in s :
s[i] = 1
else:
s[i] += 1
list = list(s.items())
list1 = sorted(list,key=lambda x:x[1],reverse=True)
print(list1[0:10])
f.close()#关闭文件

二。os模块
import os

1.返回操作系统类型 值为:posix 是linux操作系统
值为nt 是windows操作系统
print(os.name)
print(‘Linux‘ if os.name == ‘posix‘ else ‘Windows‘)

2.操作系统的详细信息
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)

3.系统的环境变量
print(os.environ)
通过key值获取环境变量对应的value值
print(os.environ.get(‘PATH‘))

4.判断是否是绝对路径
print(os.path.isabs(‘/tmp/ffff‘))
print(os.path.isabs(‘hello.jog‘))

5.生成绝对路径
print(os.path.abspath(‘hello.png‘))
print(os.path.join(os.path.abspath(‘.‘),‘hello.jpg‘))
print(os.path.join(‘/home/kiosk‘,‘hello.jpg‘))

6.获取目录或文件名
filename = ‘/home/dd/20190523/day06/hello.jpg‘
print(os.path.basename(filename))
print(os.path.dirname(filename))

7.创建目录
mkdir mkdir -p
os.mkdir(‘img‘)
os.makedirs(‘img/file1/file2‘)
不能传归删除目录
os.rmdir(‘img‘)

8.创建文件 删除文件
os.mknod(‘00_ok.txt‘)
os.remove(‘00_ok.txt‘)

9.文件重命名
os.rename(‘data.txt‘,‘data1.txt

10.判断文件或目录是否存在
print(os.path.exists(‘ips.txtyyyy‘))

11.分离后缀名和文件名
print(os.path.splitext(‘hello.jpg‘))

12.将目录名和文件名分离
print(os.path.split(‘/tmp/hello/hello.jpg‘))

原文地址:https://blog.51cto.com/12893781/2405218

时间: 2024-08-02 12:56:18

python中文件的读取与写入以及os模块的相关文章

java中文件的读取和写入

//首先要顶一个file文件用来存放要读取的文件 File f=new File("c:/test/aa.txt"); //在实例化一个输入流,并把文件对象传到里面 FileInputStream inputStream=new FileInputStream(f); //定义一个字节数组,用来存放读取的内容 byte [] b=new byte[(int)f.length()]; int len=0; int temp=0; while((temp=inputStream.read(

python 中文件输入输出及os模块对文件系统的操作

整理了一下python 中文件的输入输出及主要介绍一些os模块中对文件系统的操作. 文件输入输出 1.内建函数open(file_name,文件打开模式,通用换行符支持),打开文件返回文件对象. 2.对打开文件进行读取时,readline()与readlines()的区别在于是否一次性的读取所有的内容,并将每行的信息作为列表中的一个子项. 例如:文件test.txt中 1,3,4 2,35,6 分别用readline与readlines对其进行读取 r=file_object.readline(

python中文件操作的其他方法

前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r',encoding='utf-8')for i in p:print(i)结果如下: hello,everyone白日依山尽,黄河入海流.欲穷千里目,更上一层楼. 1.readline   #读取一行内容 p=open('poems','r',encoding='utf-8') print(p.rea

PHP 大文件的读取和写入问题

在通常的学习和开发中,因为我们很少会接触到大量数据的读取和写入,所以当突然有了这种需求的时候,我们可 能仍然会按照一些比较快捷的方法,像file_get_contents,fread等方法来读取文件,不过这样以来如果读取的文件太 大,就会产生问题,在实现大文件读取和写入的时候查找了网上的一些资料,不过有些例子给的不是很符合我的需 求,所以我就结合网上已有的例子,再写一篇总结性的博客吧. 那么究竟会产生什么问题呢,这就要说一些PHP的底层实现数,file_get_contents和fread来说一

Java I/O---RandomAccessFile类(随机访问文件的读取和写入)

1.JDK API中RandomAccessFile类的描述 此类的实例支持对随机访问文件的读取和写入.随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组.存在指向该隐含数组的光标或索引,称为文件指针:输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针.如果随机访问文件以读取/写入模式创建,则输出操作也可用:输出操作从文件指针开始写入字节,并随着对字节的写入而前移此文件指针.写入隐含数组的当前末尾之后的输出操作导致该数组扩展.该文件指针(实现数组随机读写)可以通过

python中文件的复制

python中文件的复制 python的os模块有很多文件目录相关的函数,但没有提供直接复制文件的函数,当然可以通过边都边写的方式复制文件.想要直接复制文件可以通过shutil模块 shutil模块是另一个文件,目录的管理接口,提供了一些用于复制文件,目录的函数.copyfile()函数可以实现文件的拷贝,声明如下: import shutil copyfile(src, des) 文件的剪切可以使用move()函数模拟,声明如下: move(src,des) 功能:移动一个文件或者目录到指定的

python中文件变化监控-watchdog

在python中文件监控主要有两个库,一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一个是watchdog(http://pythonhosted.org/watchdog/).pyinotify依赖于Linux平台的inotify,后者则对不同平台的的事件都进行了封装.因为我主要用于Windows平台,所以下面着重介绍watchdog(推荐大家阅读一下watchdog实现源码,有利于深刻的理解其中的原理). watchdog在

java 中文件的读取File、以及相对路径的问题

内容转自: https://blog.csdn.net/fk1778770286/article/details/53900636 1 Properties properties = new Properties(); 2 InputStream is = DBUtils.class.getResourceAsStream("jdbc.properties"); 以下写法,从class根目录查找文件 1 Properties properties= new Properties();

python中关于不执行if __name__ == &#39;__main__&#39;:测试模块的解决

1.新建测试脚本文件: 2.编辑测试脚本 import unittest import requests import json import HTMLTestRunner ur1 = 'http://118.178.247.67:8081/systLogonUser/adminLogon.do' headers = {'Content-Type':'application/x-www-form-urlencoded','Referer':'118.178.247.67'} data = { '