当前位置: 首页 > news >正文

梅州正规的免费建站网站如何seo推广

梅州正规的免费建站,网站如何seo推广,网站的建设需要虚拟机吗,兼职做效果图设计到哪个网站找一、【基本的文件操作】 参数: 1、文件路径; 2、编码方式; 3、执行动作;(打开方式)只读,只写,追加,读写,写读! #1. 打开文件,得到文件…

一、【基本的文件操作】

参数:
1、文件路径;
2、编码方式;
3、执行动作;(打开方式)只读,只写,追加,读写,写读!

#1. 打开文件,得到文件句柄并赋值给一个变量
f = open('E:/Python/file/文件操作测试.txt', encoding='utf-8', mode='r')
content = f.read()
print(content)
f.close()E:\Python\venv\Scripts\python.exe E:/Python/day08/文件操作.py
文件操作测试读取,2018-3-27
readf:变量,f_obj,file,f_handler,...文件句柄。
open --- windows的系统功能,
windows默认编码方式:gbk,
linux默认编码方式:utf-8。
f.close() --- 关闭文件(保存退出)

流程:
1、打开一个文件,产生一个文件句柄,
2、通过句柄对文件进行操作,
3、关闭文件。

二、【关闭文件的注意事项】

打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。
在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
1、f.close() #回收操作系统级打开的文件
2、del f #回收应用程序级的变量

其中del f一定要发生在f.close()之后,
否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
python自动的垃圾回收机制决定了无需考虑del f,在操作完毕文件后,记住f.close()就可以了。

推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文的同时自动关闭文件。

【with】
功能一:自动关闭文件句柄
功能二:一次性操作多个文件句柄

例:

with open('a.txt', encoding='utf-8', 'w') as f:passwith open('a.txt', encondig='utf-8', 'w') as read_f,open('b.txt','w') as write_f:data=read_f.read()write_f.write(data)

三、【文件的打开模式】

文件句柄 = open(‘文件路径’,‘模式’)

1、文件以什么编码方式存储的,就以什么编码方式打开;
2、文件路径:
绝对路径:从根目录开始
相对路径:从打开软件所在的路径开始(比如pycharm就是在pycharm的工作目录起)

1. 打开文件的模式有(默认为文本模式):

r, 只读模式【默认模式,文件必须存在,不存在则抛出异常】
w, 只写模式【不可读;文件不存在则创建文件;存在则清空内容】
a, 只追加写模式【不可读;文件不存在则创建;存在则只追加内容】

2. 对于非文本文件,(例如图片)可以使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)

rb
wb
ab
具体同上,只是后面加了个b表示是b模式。
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码。

3,‘+’模式(就是增加了一个功能)

r+, 读写【可读,可写】
w+, 写读【可写,可读】
a+, 追加方式的写读【可写,可读】

4,以bytes类型操作的读写,写读,写读模式

r+b, 读写【可读,可写】
w+b, 写读【可写,可读】
a+b, 追加写读【可写,可读】

四、【文件操作方式】

【读模式操作方式】
read()
全部一次性读取(有缺点:要是一次性读取超大文件会爆内存,例如linux上的日志文件。)

readline()
每次读取一行(并且文件内光标随之移动到第二行头部)

readlines()
将原文件的每一行作为一个元素放在列表当中(包括\n换行符)可加.strip去掉换行符

read(n)
在r模式下,按字符去读取n个字符
在rb模式下,按字节去读取n个字节

适合读取超大文件的方法:
循环读取,全部能读取出来而且在内存当中永远只占一行。
因为每次都是读取一行清除一行的内存在去读取下一行。

例:循环读取。

# f = open('log',encoding='utf-8')
# for i in f:
#     print(i.strip())
# f.close()

【光标】
文件内光标移动都是以字节为单位的如:seek,tell,truncate
f.tell() # 按字节去读取光标位置
f.seek() # 按字节调整光标位置

file.seek()方法格式:
seek(offset,whence=0)
移动文件读取指针(移动光标)到指定位置。

offset:开始的偏移量,也就是代表需要移动偏移的字节数。

whence(移动模式): 给offset参数一个定义,表示要从哪个位置开始偏移;
0代表从文件开头算起,
1代表开始从当前位置开始算起,
2代表从文件末尾开始算起。当有换行时,会被换行截断。

seek的三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的。
seek()无返回值,故值为None

file.truncate():
truncate(),对文字内容进行截取。
truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,
因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。

【官方源码参考】

class file(object)def close(self): # real signature unknown; restored from __doc__关闭文件"""close() -> None or (perhaps) an integer.  Close the file.Sets data attribute .closed to True.  A closed file cannot be used forfurther I/O operations.  close() may be called more than once withouterror.  Some kinds of file objects (for example, opened by popen())may return an exit status upon closing."""def fileno(self): # real signature unknown; restored from __doc__文件描述符  """fileno() -> integer "file descriptor".This is needed for lower-level file interfaces, such os.read()."""return 0    def flush(self): # real signature unknown; restored from __doc__刷新文件内部缓冲区(类似于文件-保存的效果)""" flush() -> None.  Flush the internal I/O buffer. """passdef isatty(self): # real signature unknown; restored from __doc__判断文件是否是同意tty设备""" isatty() -> true or false.  True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__获取下一行数据,不存在,则报错""" x.next() -> the next value, or raise StopIteration """passdef read(self, size=None): # real signature unknown; restored from __doc__读取指定字节数据"""read([size]) -> read at most size bytes, returned as a string.If the size argument is negative or omitted, read until EOF is reached.Notice that when in non-blocking mode, less data than what was requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__读取到缓冲区,不要用,将被遗弃""" readinto() -> Undocumented.  Don't use this; it may go away. """passdef readline(self, size=None): # real signature unknown; restored from __doc__仅读取一行数据"""readline([size]) -> next line from the file, as a string.Retain newline.  A non-negative size argument limits the maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef readlines(self, size=None): # real signature unknown; restored from __doc__读取所有数据,并根据换行保存值到列表"""readlines([size]) -> list of strings, each a line from the file.Call readline() repeatedly and return a list of the lines so read.The optional size argument, if given, is an approximate bound on thetotal number of bytes in the lines returned."""return []def seek(self, offset, whence=None): # real signature unknown; restored from __doc__指定文件中指针位置"""seek(offset[, whence]) -> None.  Move to new file position.Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1(move relative to current position, positive or negative), and 2 (moverelative to end of file, usually negative, although many platforms allowseeking beyond the end of a file).  If the file is opened in text mode,only offsets returned by tell() are legal.  Use of other offsets causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__获取当前指针位置""" tell() -> current file position, an integer (may be a long integer). """passdef truncate(self, size=None): # real signature unknown; restored from __doc__截断数据,仅保留指定之前数据"""truncate([size]) -> None.  Truncate the file to at most size bytes.Size defaults to the current file position, as returned by tell()."""passdef write(self, p_str): # real signature unknown; restored from __doc__写内容"""write(str) -> None.  Write string str to file.Note that due to buffering, flush() or close() may be needed beforethe file on disk reflects the data written."""passdef writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__将一个字符串列表写入文件"""writelines(sequence_of_strings) -> None.  Write the strings to the file.Note that newlines are not added.  The sequence can be any iterable objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__可用于逐行读取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations previously implemented in the xreadlines module."""pass

五、【文件的修改】

文件的数据是存放于硬盘上的,因而实际上底层只存在覆盖、不存在修改这么一说,
我们平时看到的修改编辑文件,都是模拟出来的效果,具体的说有两种实现方式:

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

---------------------------
import os  # 调用系统模块with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:data=read_f.read() #全部读入内存,如果文件很大,会很卡data=data.replace('old','new') #在内存中完成修改,将旧内容替换成新内容write_f.write(data) #一次性写入新文件os.remove('a.txt')  #删除原文件
# 因为不删除将建立不了同名的文件,其实我感觉上先将原文件改名再让新文件命名成原文件名后确认无误后再删除原文件更安全保险。
os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件
-----------------------------

方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件。

import oswith open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:for line in read_f:line=line.replace('old','new')write_f.write(line)os.remove('a.txt')
os.rename('.a.txt.swap','a.txt') 

简述为以下流程:
1、将源文件读取到内存;
2、在内存中时行修改,形成新的字符串(文件);
3、将新的字符串写入新文件;
3、将原文件删除;
4、将新文件重命名为原文件。

例:有如下文件:
-------
alex是老男孩python发起人,创建人。
alex其实是人妖。
谁说alex是sb?
你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。
----------
将文件中所有的alex都替换成大写的SB。答:with open('log',encoding='utf-8') as f1,\open('log.bak',encoding='utf-8',mode='w') as f2:content = f1.read()new_content = content.replace('alex','SB')f2.write(new_content)
os.remove('log')
os.rename('log.bak','log')import os
with open('log',encoding='utf-8') as f1,\open('log.bak',encoding='utf-8',mode='w') as f2:for i in f1:new_i = i.replace('SB','alex')f2.write(new_i)
os.remove('log')
os.rename('log.bak','log')

end
2018-4-2

转载于:https://www.cnblogs.com/tielemao/p/8698478.html

http://www.lbrq.cn/news/2356399.html

相关文章:

  • 泰州网站制作人工智能培训课程
  • 连云港北京网站建设网站seo关键词优化排名
  • html项目模板下载宁波优化网站排名软件
  • 汽车网站模版360站长工具seo
  • 郑州网站制作公免费域名申请网站
  • 手机做logo用什么网站今日新闻最新
  • 商城网站建设排名企业推广视频
  • 专业网站建设的价格360收录提交入口
  • 安陆市城乡建设局网站100条经典广告语
  • 小程序开发平台花多少钱宁波seo网站排名优化公司
  • 广州做网站最好的公司深圳百度推广联系方式
  • 香港服务器做收费网站要付税吗16种营销模型
  • 中国建设银行官网站贺岁产品北京网站制作公司
  • php网站开发结构青岛网络推广
  • 怎么在一个网站做多个页面快链友情链接平台
  • 网站制作时间代码济南百度
  • 网站主机空间引流app推广软件
  • 东莞网站建设制作服务日本疫情最新数据
  • 网站是软件吗百度账号登录入口
  • 网站的主要栏目及功能网站seo优化服务
  • 网站开发的售后 维保新乡网站推广
  • 百度云服务器做asp网站南宁seo主管
  • 代理 指定网站 host宁波网络优化seo
  • 一级a做爰片付费网站高端企业网站定制公司
  • 做英文网站软件培训机构排名
  • 邯山手机网站建设网站的优化策略方案
  • 简单学校网站模板长沙网站优化公司
  • 技术支持 武汉网站建设百度问问首页
  • 大连企业公司网站建设小说推广关键词怎么弄
  • 网站维护提示页面模板外贸网站seo教程
  • (李宏毅)deep learning(五)--learning rate
  • leetGPU解题笔记(2)
  • 串口A和S的含义以及RT的含义
  • 直播录屏技术揭秘:以抖音直播录屏为例
  • python库之jieba 库
  • 一文理解锂电池充电、过放修复与电量测量:从原理到实战