一、文件操作步骤

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
  1. 歌名:《大火》
  2. 演唱:李佳薇
  3. 作词:姚若龙
  4. 作曲:马奕强
  5. 歌词:
  6. 有座巨大的停了的时钟
  7. 倾倒在赶路的途中 挡我 向前走
  8. 有只黑色的老鹰在俯冲
  9. 叼走了你送的承诺 回头 冷冷看我
  10. 有阵将眼泪扫落的狂风
  11. 掀起了隐藏的疼痛 把我 变赤裸
  12. 我为蔓延的回忆除草了
  13. 心中却长出盛开的 寂寞 原来是梦
  14. 有些伤痕像场大火 把心烧焦难以复活
  15. 不碰了好像忘了 恐惧却在脑海住着
  16. 重复卡在一个 重要的时刻 不自觉就会退缩
  17. 连幸福也克制着 觉得什麽都会变的
  18. 防备着平静到最後 连爱也透着冷漠
  19. 有人说我的微笑是暖的
  20. 心里却很难被感动 狠狠 解剖我
  21. 从不是有意想害谁难过
  22. 甚至会沮丧一直没突破 沉重的壳
  23. 有些伤痕像场大火 把心烧焦难以复活
  24. 不碰了好像忘了 恐惧却在脑海住着
  25. 重复卡在一个 重要的时刻 不自觉就会退缩
  26. 连幸福也克制着 觉得什麽都会变的
  27. 防备着平静到最後 独自寂寞
  28. 有些伤痕像场大火 把心烧焦难以复活
  29. 可是我 想要忘了 恐惧如何把我上锁
  30. 期待阳光炽热 爱来的时刻 能用力去拥抱着
  31. 多幸福就多快乐 不让未知成为负荷
  32. 投入的留下了每一刻 不怕的人 最富有
  33. 人太脆弱 会不停错过
  34. 太多宝贵的 都需要跋涉 才可以获得
  35. 太多璀璨的 越隔着夜色 越光芒四射

示范文件内容

二、文件操作详解

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件

1. 打开或关闭文件

open 函数

你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。

语法:

  1. file object = open(file_name [, access_mode][, buffering])

  各个参数的细节如下:

  • file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
  • access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
  • buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

注: python中打开文件有两种方式,即:open(...) 和  file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

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

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码。

2. File对象的属性

一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。

以下是和file对象相关的所有属性的列表:

file.closed 返回true如果文件已被关闭,否则返回false。
file.mode 返回被打开文件的访问模式。
file.name 返回文件的名称。
file.softspace 如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

如下实例:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. # 打开一个文件
  5. fo = open("foo.txt", "wb")
  6. print "文件名: ", fo.name
  7. print "是否已关闭 : ", fo.closed
  8. print "访问模式 : ", fo.mode
  9. print "末尾是否强制加空格 : ", fo.softspace

3. 文件操作函数

  1. class file(object):
  2.  
  3. def close(self): # real signature unknown; restored from __doc__
  4. 关闭文件
  5. """
  6. close() -> None or (perhaps) an integer. Close the file.
  7.  
  8. Sets data attribute .closed to True. A closed file cannot be used for
  9. further I/O operations. close() may be called more than once without
  10. error. Some kinds of file objects (for example, opened by popen())
  11. may return an exit status upon closing.
  12. """
  13.  
  14. def fileno(self): # real signature unknown; restored from __doc__
  15. 文件描述符
  16. """
  17. fileno() -> integer "file descriptor".
  18.  
  19. This is needed for lower-level file interfaces, such os.read().
  20. """
  21. return 0
  22.  
  23. def flush(self): # real signature unknown; restored from __doc__
  24. 刷新文件内部缓冲区
  25. """ flush() -> None. Flush the internal I/O buffer. """
  26. pass
  27.  
  28. def isatty(self): # real signature unknown; restored from __doc__
  29. 判断文件是否是同意tty设备
  30. """ isatty() -> true or false. True if the file is connected to a tty device. """
  31. return False
  32.  
  33. def next(self): # real signature unknown; restored from __doc__
  34. 获取下一行数据,不存在,则报错
  35. """ x.next() -> the next value, or raise StopIteration """
  36. pass
  37.  
  38. def read(self, size=None): # real signature unknown; restored from __doc__
  39. 读取指定字节数据
  40. """
  41. read([size]) -> read at most size bytes, returned as a string.
  42.  
  43. If the size argument is negative or omitted, read until EOF is reached.
  44. Notice that when in non-blocking mode, less data than what was requested
  45. may be returned, even if no size parameter was given.
  46. """
  47. pass
  48.  
  49. def readinto(self): # real signature unknown; restored from __doc__
  50. 读取到缓冲区,不要用,将被遗弃
  51. """ readinto() -> Undocumented. Don't use this; it may go away. """
  52. pass
  53.  
  54. def readline(self, size=None): # real signature unknown; restored from __doc__
  55. 仅读取一行数据
  56. """
  57. readline([size]) -> next line from the file, as a string.
  58.  
  59. Retain newline. A non-negative size argument limits the maximum
  60. number of bytes to return (an incomplete line may be returned then).
  61. Return an empty string at EOF.
  62. """
  63. pass
  64.  
  65. def readlines(self, size=None): # real signature unknown; restored from __doc__
  66. 读取所有数据,并根据换行保存值列表
  67. """
  68. readlines([size]) -> list of strings, each a line from the file.
  69.  
  70. Call readline() repeatedly and return a list of the lines so read.
  71. The optional size argument, if given, is an approximate bound on the
  72. total number of bytes in the lines returned.
  73. """
  74. return []
  75.  
  76. def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
  77. 指定文件中指针位置
  78. """
  79. seek(offset[, whence]) -> None. Move to new file position.
  80.  
  81. Argument offset is a byte count. Optional argument whence defaults to
  82. 0 (offset from start of file, offset should be >= 0); other values are 1
  83. (move relative to current position, positive or negative), and 2 (move
  84. relative to end of file, usually negative, although many platforms allow
  85. seeking beyond the end of a file). If the file is opened in text mode,
  86. only offsets returned by tell() are legal. Use of other offsets causes
  87. undefined behavior.
  88. Note that not all file objects are seekable.
  89. """
  90. pass
  91.  
  92. def tell(self): # real signature unknown; restored from __doc__
  93. 获取当前指针位置
  94. """ tell() -> current file position, an integer (may be a long integer). """
  95. pass
  96.  
  97. def truncate(self, size=None): # real signature unknown; restored from __doc__
  98. 截断数据,仅保留指定之前数据
  99. """
  100. truncate([size]) -> None. Truncate the file to at most size bytes.
  101.  
  102. Size defaults to the current file position, as returned by tell().
  103. """
  104. pass
  105.  
  106. def write(self, p_str): # real signature unknown; restored from __doc__
  107. 写内容
  108. """
  109. write(str) -> None. Write string str to file.
  110.  
  111. Note that due to buffering, flush() or close() may be needed before
  112. the file on disk reflects the data written.
  113. """
  114. pass
  115.  
  116. def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
  117. 将一个字符串列表写入文件
  118. """
  119. writelines(sequence_of_strings) -> None. Write the strings to the file.
  120.  
  121. Note that newlines are not added. The sequence can be any iterable object
  122. producing strings. This is equivalent to calling write() for each string.
  123. """
  124. pass
  125.  
  126. def xreadlines(self): # real signature unknown; restored from __doc__
  127. 可用于逐行读取文件,非全部
  128. """
  129. xreadlines() -> returns self.
  130.  
  131. For backward compatibility. File objects now include the performance
  132. optimizations previously implemented in the xreadlines module.
  133. """
  134. pass

  

3.1 file(文件方法)

  • 以下是文件操作的常用方法
1

file.close()   关闭文件。关闭后文件不能再进行读写操作。

2

file.flush()   刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。

3

file.fileno()   返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。

4

file.isatty()   如果文件连接到一个终端设备返回 True,否则返回 False。

5

file.next()   返回文件下一行。

6

file.read([size])   从文件读取指定的字节数,如果未给定或为负则读取所有。

7

file.readline([size])    读取整行,包括 "\n" 字符。

8

file.readlines([sizeint])    读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。

9

file.seek(offset[, whence])   设置文件当前位置

10

file.tell()   返回文件当前位置。

11

file.truncate([size])     截取文件,截取的字节通过size指定,默认为当前文件位置。

12

file.write(str)    将字符串写入文件,没有返回值。

13

file.writelines(sequence)   向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

3.2 文件内置函数flush

flush原理:

  1. 文件操作是通过软件将文件从硬盘读到内存。
  2. 写入文件的操作也都是存入内存缓冲区buffer(内存速度快于硬盘,如果写入文件的数据都从内存刷到硬盘,内存与硬盘的速度延迟会被无限放大,效率变低,所以要刷到硬盘的数据我们统一往内存的一小块空间即buffer中放,一段时间后操作系统会将buffer中数据一次性刷到硬盘)
  3. flush即,强制将写入的数据刷到硬盘。

滚动条:

  1. import sys,time
  2.  
  3. for i in range(10):
  4. sys.stdout.write('#')
  5. sys.stdout.flush()
  6. time.sleep(0.2)

3.3 文件光标移动

tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后。

seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。

如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

seek():移动文件读取指针到指定位置,设置文件当前位置。

tell():返回文件读取指针的位置。

seek()的三种模式:

(1)f.seek(p,0)  移动当文件第p个字节处,绝对位置

(2)f.seek(p,1)  移动到相对于当前位置之后的p个字节

(3)f.seek(p,2)  移动到相对文章尾之后的p个字节

例子:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. # 打开一个文件
  5. fo = open("foo.txt", "r+")
  6. str = fo.read(10);
  7. print "读取的字符串是 : ", str
  8.  
  9. # 查找当前位置
  10. position = fo.tell();
  11. print "当前文件位置 : ", position
  12.  
  13. # 把指针再次重新定位到文件开头
  14. position = fo.seek(0, 0);
  15. str = fo.read(10);
  16. print "重新读取字符串 : ", str
  17. # 关闭打开的文件
  18. fo.close()

注:read(3)代表读取3个字符,其余的文件内光标移动都是以字节为单位如seek,tell,read,truncate

3.4 open函数详解

1. open()语法
open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
open函数有很多的参数,常用的是file,mode和encoding
file文件位置,需要加引号
mode文件打开模式,见下面3
buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;
encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。
newline可以取的值有None, \n, \r, ”, ‘\r\n',用于区分换行符,但是这个参数只对文本模式有效;
closefd的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。

2. Python中file()与open()区别

两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,file为文件类,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,建议使用open

3. 参数mode的基本取值

Character Meaning
‘r' open for reading (default)
‘w' open for writing, truncating the file first
‘a' open for writing, appending to the end of the file if it exists
‘b' binary mode
‘t' text mode (default)
‘+' open a disk file for updating (reading and writing)
‘U' universal newline mode (for backwards compatibility; should not be used in new code)

r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;

b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用;

r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

4. 常见的mode取值组合

  1. rrt 默认模式,文本模式读
  2. rb 二进制文件
  3.  
  4. wwt 文本模式写,打开前文件存储被清空
  5. wb 二进制写,文件存储同样被清空
  6.  
  7. a 追加模式,只能写在文件末尾
  8. a+ 可读写模式,写只能写在文件末尾
  9.  
  10. w+ 可读写,与a+的区别是要清空文件内容
  11. r+ 可读写,与a+的区别是可以写到文件任何位置

3.5 上下文管理

  1. with open('a.txt','w') as f: # 如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
       pass
  1. with open('a.txt','r') as read_f,open('b.txt','w') as write_f: #在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
  2. data=read_f.read()
  3. write_f.write(data)

3.6 模拟tail -f命令 功能

  1. import time
  2. with open('access.log','r',encoding='utf-8') as f:
  3. f.seek(0,2)        # 打开文件后立刻将光标移动至文件末尾
  4. while True:
  5. line=f.readline().strip()
  6. if line:
  7. print('新增一行日志',line)
  8. time.sleep(0.5)

3.7  文件的修改

  1. import os
  2. with open('a.txt','r',encoding='utf-8') as read_f,\
  3. open('.a.txt.swap','w',encoding='utf-8') as write_f:
  4. for line in read_f:
  5. if line.startswith('hello'):
  6. line='哈哈哈\n'
  7. write_f.write(line)
  8.  
  9. os.remove('a.txt')
  10. os.rename('.a.txt.swap','a.txt')

那么问题来了...

1、如何在线上环境优雅的修改配置文件?

  1. global
  2. log 127.0.0.1 local2
  3. daemon
  4. maxconn 256
  5. log 127.0.0.1 local2 info
  6. defaults
  7. log global
  8. mode http
  9. timeout connect 5000ms
  10. timeout client 50000ms
  11. timeout server 50000ms
  12. option dontlognull
  13.  
  14. listen stats :8888
  15. stats enable
  16. stats uri /admin
  17. stats auth admin:1234
  18.  
  19. frontend oldboy.org
  20. bind 0.0.0.0:80
  21. option httplog
  22. option httpclose
  23. option forwardfor
  24. log global
  25. acl www hdr_reg(host) -i www.oldboy.org
  26. use_backend www.oldboy.org if www
  27.  
  28. backend www.oldboy.org
  29. server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
  30.  
  31. 原配置文件

原配置文件

  1. 1、查
  2. 输入:www.oldboy.org
  3. 获取当前backend下的所有记录
  4.  
  5. 2、新建
  6. 输入:
  7. arg = {
  8. 'bakend': 'www.oldboy.org',
  9. 'record':{
  10. 'server': '100.1.7.9',
  11. 'weight': 20,
  12. 'maxconn': 30
  13. }
  14. }
  15.  
  16. 3、删除
  17. 输入:
  18. arg = {
  19. 'bakend': 'www.oldboy.org',
  20. 'record':{
  21. 'server': '100.1.7.9',
  22. 'weight': 20,
  23. 'maxconn': 30
  24. }
  25. }
  26.  
  27. 需求

需求

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import os
  4.  
  5. def query(content):
  6. '''
  7. 功能: 根据用户传入的域名查找相关的配置信息,返回一个列表
  8. :param content: 用户输入的域名
  9. :return: data
  10. '''
  11. res_list = []
  12. content = 'backend %s' % content
  13. with open('haproxy.conf', 'r', encoding='utf-8') as fo:
  14. flag = False
  15. for line in fo:
  16. line = line.strip()
  17. if line.startswith('backend') and content == line:
  18. flag = True
  19. continue
  20. if flag:
  21. res_list.append(line)
  22. flag = False
  23. continue
  24. return res_list
  25.  
  26. def add(content):
  27. '''
  28. 功能: 获取用户输入内容并写入文件
  29. :param content:
  30. :return:
  31. '''
  32. # 用于存放写入文件内容的列表
  33. data_list = []
  34. data_dic = eval(content)
  35. # print('转化为字典: ', data_dic)
  36. backend = data_dic.get('backend')
  37. server = data_dic.get('record')
  38. server_con = "server {} {} weight {} maxconn {}".format(server['server'], server['server'], server['weight'],
  39. server['maxconn'])
  40. query_list = query(backend)
  41. if server_con in query_list:
  42. print('\033[1;31m内容已存在!\033[0m')
  43. else:
  44. ele = 'backend %s' % backend
  45. data_list.append(ele)
  46. data_list.append(server_con)
  47. with open('haproxy.conf','a+',encoding='utf-8') as fo:
  48. for item in data_list:
  49. if item.strip().startswith('backend'):
  50. fo.write('\n')
  51. fo.write("\n%s\n" % item)
  52. else:
  53. fo.write('\t\t%s' % item)
  54. print('\033[1;32m写入成功!\033[0m')
  55.  
  56. def remove(content):
  57. """
  58. 功能: 查找到用户输入的内容并删除
  59. :param content:
  60. :return:
  61. """
  62. data_dic = eval(content)
  63. backend_con = data_dic.get('backend')
  64. server_dic = data_dic.get('record')
  65. data = "server {} {} weight {} maxconn {}".format(server_dic['server'], server_dic['server'],
  66. server_dic['weight'], server_dic['maxconn'])
  67. match = "backend %s" % backend_con
  68. data_list = query(backend_con)
  69. # print("query: ", data_list)
  70. if not data_list or data not in data_list:
  71. print("\033[1;31m内容不存在!\033[0m")
  72. return
  73. elif data in data_list:
  74. flag = False
  75. with open('haproxy.conf', encoding='utf-8') as read_f, open('ha.swap', 'w', encoding='utf-8') as write_f:
  76. for line in read_f:
  77. line = line.strip()
  78. if line.startswith('backend') and match == line:
  79. flag = True
  80. continue
  81. if flag and data == line:
  82. flag = False
  83. continue
  84. elif flag and data != line:
  85. flag = False
  86. write_f.write('%s\n' % match)
  87. if not flag:
  88. write_f.write('%s\n' % line)
  89. print('删除成功!')
  90. os.rename("haproxy.conf","haproxy.conf_bak")
  91. os.rename("ha.swap","haproxy.conf")
  92.  
  93. if __name__ == '__main__':
  94. info = """
  95. 1. 查询
  96. 2. 增加
  97. 3. 删除
  98. 4. 退出
  99. """
  100. print(info)
  101. menu_dic = {
  102. '': query,
  103. '': add,
  104. '': remove,
  105. '': exit
  106. }
  107. while True:
  108. choice = input("请选择您需要操作的id: ").strip()
  109. if not choice or choice not in menu_dic: continue
  110. if choice == '': break
  111. content = input("请输入内容: ").strip()
  112. # content = "{'backend': 'www.oldboy.org','record':{'server': '100.1.7.9','weight': 20,'maxconn': 300}}"
  113. # content = "www.oldboy.org"
  114. if choice == '':
  115. res_list = menu_dic[choice](content) # 用choice作为key,从字典中获取到对应的函数对象后加(),即调用函数,将content作为参数传入函数
  116. if res_list:
  117. print("\033[1;32m查询的结果为:\033[0m %s" % res_list)
  118. else:
  119. print("\033[1;31m未查找到内容\033[0m")
  120. else:
  121. menu_dic[choice](content)

demo

详细参考: http://www.runoob.com/python/python-files-io.html

Python之路【第三篇】:文件操作的更多相关文章

  1. python学习笔记——(三)文件操作

    ·集合操作及其相应的操作符表示集合中没有插入,只有添加,因为毕竟无序 #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Vergil Zhan ...

  2. python学习笔记(三)— 文件操作

    对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件 3.关闭文件. 现有以下文件a.txt: 登鹳雀楼 唐代:王之涣 白日依山尽,黄河入海流. 一.文件基 ...

  3. python之路(5)文件操作(open)

      目录 前言 文件的打开模式 文件句柄的方法 seek()方法介绍 前言 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 f = open('demo.txt','r',e ...

  4. GIT学习之路第三天 文件操作

    本文参考廖雪峰老师的博客进行总结,完整学习请转廖雪峰博客 一.版本回退 1.git log提交日志 在git中可以通过个git log 命令显示从最近到最远的提交日志. $ git log commi ...

  5. Python之路(第三篇):Python基本数据类型字符串(二)

    一.基本数据类型1.字符串 str字符串方法介绍(二)a --expandtabs( ) expandtabs( ) 把字符串中的 tab 符号('\t')转为空格参数默认为8,注意字符串原有的空格也 ...

  6. Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy   Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用 ...

  7. Python入门篇-文件操作

    Python入门篇-文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.文件IO常用操作 open:打开 read:读取 write:写入 close:关闭 readlin ...

  8. python基础篇(文件操作)

    Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...

  9. Python学习系列(五)(文件操作及其字典)

    Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件      在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...

  10. iOS开发——C篇&文件操作

    今天开始C语言中的重点难点就基本上技术忘了,但是还有最后一个知识点不得不提,那就是文件操作. 我们都知道,我们每天都在使用电脑,手机,或者其他电子或者移动设备,其实我们在使用的时候每时每刻都在执行文件 ...

随机推荐

  1. Tensorboard教程:显示计算图中节点信息

    Tensorboard显示计算图节点信息 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 强烈推荐Tensorflow实战Google深度学习框架 实验平台: Tensorflow1 ...

  2. UITableView .grouped 类型去除顶部间距

    在设置 UITableView 的 style 为 .grouped 类型的时候,发现第一个 cell 的顶部存在大段的间距,而改为 .plain 类型则没有这个间距,效果如下: 设置了 conten ...

  3. npm 的使用指南

    npm 使用指南 因为有写关于node.js的配置的博客,还有node和gulp的前端信息配置使用,其中有很多命令都用到了npm.所以这里要着重介绍一下npm. 1 npm介绍 npm(mode pa ...

  4. 优先队列 逆向思维 Gym 101128C

    题目链接:http://codeforces.com/gym/101128/my 具体题目大意可以看这个人的:http://blog.csdn.net/v5zsq/article/details/61 ...

  5. Spring Boot 使用IntelliJ IDEA创建一个web开发实例(三)

    属性配置 1.配置application.properties文件 配置web访问端口和context path server.port = 8081 server.servlet.context-p ...

  6. easyui 更改dialog弹出的位置

    方法一: 在弹出dialog的时候不用$('#dialogDiv').dialog('open');打开.用$('#dialogDiv').window('open');打开.再用window的res ...

  7. protoc

    平台安装: 在window 平台使用的工具protoc.zip linux平台的安装方式. 执行在windos平台上执行生成java代码命令: protoc --java_out=./ Keyword ...

  8. ArrayList既然继承自AbstractList抽象类,而AbstractList已经实现了List接口,那么ArrayList类为何还要再实现List接口呢?

    https://www.cnblogs.com/bluejavababy/p/4320545.html

  9. django【ORM】 通过外键字段找对应类

    两个方法其实是一种,用哪个都行,看实例:   方法一: 从list_filter中的字符串,找到model对象的字段,然后得到这个外键对应的类 循环,把list_filter中对应的类所有对象 方法二 ...

  10. 设计模式之笔记--外观模式(Facade)

    外观模式(Facade) 定义 外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用. 类图 描述 Facade:外观类,外观 ...