博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 学习笔记(二)文件操作
阅读量:6174 次
发布时间:2019-06-21

本文共 3629 字,大约阅读时间需要 12 分钟。

Files

  • File iterators are best for reading lines
  • Content is strings, not objects
  • close is usually optional
  • Files are buffered and seekable.
>>> myfile = open('myfile.txt', 'w') # Open for text output: create/empty>>> myfile.write('hello text file\n') # Write a line of text: string16  #length>>> myfile.write('goodbye text file\n')18>>> myfile.close() # Flush output buffers to disk>>> myfile = open('myfile.txt') # Open for text input: 'r' is default>>> myfile.readline() # Read the lines back'hello text file\n'
>>> for line in open('myfile.txt'):    print(line)hello text filegoodbye text file

File写入任意类型

>>> X, Y, Z = 43, 44, 45 # Native Python objects>>> S = 'Spam' # Must be strings to store in file>>> D = {
'a': 1, 'b': 2}>>> L = [1, 2, 3]>>>>>> F = open('datafile.txt', 'w') # Create output file>>> F.write(S + '\n') # Terminate lines with \n>>> F.write('%s,%s,%s\n' % (X, Y, Z)) # Convert numbers to strings>>> F.write(str(L) + '$' + str(D) + '\n') # Convert and separate with $>>> F.close()>>> chars = open('datafile.txt').read() # Raw string display>>> chars"Spam\n43,44,45\n[1, 2, 3]${'a': 1, 'b': 2}\n">>> print(chars) # User-friendly displaySpam43,44,45[1, 2, 3]${
'a': 1, 'b': 2}
>>> F = open('datafile.txt') # Open again>>> line = F.readline() # Read one line>>> line'Spam\n'>>> line.rstrip() # Remove end-of-line'Spam'
>>> int(parts[1]) # Convert from string to int44>>> numbers = [int(P) for P in parts] # Convert all in list at once>>> numbers[43, 44, 45]
>>> line = F.readline() >>> parts = line.split('$')>>> objects = [eval(P) for P in parts] # eval Convert to any object type>>> objects[[1, 2, 3], {
'a': 1, 'b': 2}]

按行遍历文件:

with open('myfile.txt') as myfile:    for line in myfile:            print(line)

 Copy

>>> L = [1,2,3]>>> D = {
'a':1, 'b':2}>>> A = L[:] # Instead of A = L (or list(L))>>> B = D.copy() # Instead of B = D (ditto for sets)

Two examples:

- Change L will change M too

>>> L = [1, 2, 3]>>> M = ['X', L, 'Y'] # Embed a reference to L>>> M['X', [1, 2, 3], 'Y']>>> L[1] = 0 # Changes M too>>> M['X', [1, 0, 3], 'Y']

- Only change L, not M

>>> L = [1, 2, 3]>>> M = ['X', L[:], 'Y'] # Embed a copy of L>>> L[1] = 0 # Changes only L, not M>>> L[1, 0, 3]>>> M['X', [1, 2, 3], 'Y']

比较相等

  • The == operator tests value equivalence.
  • The is operator tests object identity.
  •  Numbers are true if nonzero.
  • Other objects are true if nonempty.

 

Python internally caches and reuses some strings as an optimization, there really is just a single string 'hello' in

memory:

 

>>> s1='hello'>>> s2='hello'>>> s1==s2True>>> s1 is s2True>>> s1='hello world'>>> s2='hello world'>>> s1 is s2False

有意思的例子,注意嵌套的影响,tuple 与list 不同,tuple的Y与X 一样

>>> L = [4, 5, 6]>>> X = L * 4 # Like [4, 5, 6] + [4, 5, 6] + ...>>> Y = [L] * 4 # [L] + [L] + ... = [L, L,...]>>> X[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]>>> Y[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]>>> L[1] = 0 # Impacts Y but not X>>> X[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]>>> Y[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]

How to change tuple (4,5,6) to (1,5,6)

>>> T = (4,5,6)>>> T = (1,) + T[1:]>>> T(1, 5, 6)

换值

>>> X='a'>>> Y='B'>>> X,Y = Y,X>>> X'B'

赋值

>>> a, *b = 'spam' #New method in 3.0>>> b['p', 'a', 'm']
>>> L = [1,2,3,4]>>> while L:      f,*L=L  #f = L[0]      print(f,L)    1 [2, 3, 4]2 [3, 4]3 [4]4 []

赋空值,需单独

>>> a = b = []>>> b.append(42)>>> a, b([42], [42])>>> a = []>>> b = []>>> b.append(42)>>> a, b([], [42])
>>> L = [1, 2]>>> L.append(3) # Append is an in-place change>>> L[1, 2, 3]>>> L = L.append(4) # But append returns None, not L>>> print(L) # So we lose our list!None

 

转载于:https://www.cnblogs.com/zyf7630/archive/2013/05/10/3070618.html

你可能感兴趣的文章
5. GC 调优(基础篇) - GC参考手册
查看>>
Windows 7 XP 模式颜色质量只有16位的解决
查看>>
SonicWall如何安全模式升级防火墙
查看>>
Linux IPC实践(3) --具名FIFO
查看>>
从Atlas到Microsoft ASP.NET AJAX(6) - Networking, Application Services
查看>>
成长之路---写好一个类
查看>>
读取 java.nio.ByteBuffer 中的字符串(String) 写入方式flash.utils.ByteArray.writeUTF
查看>>
范围管理和范围蔓延
查看>>
android90 bind方式启动服务service调用service里的方法
查看>>
前端开发薪资之各地区对比(图文分析)(share)
查看>>
对做“互联网产品”的一些想法
查看>>
SPI协议及其工作原理浅析【转】
查看>>
原生js编写的安全色拾色器
查看>>
iOS:VFL语言
查看>>
让时间处理简单化 【第三方扩展类库org.apache.commons.lang.time】
查看>>
用scikit-learn学习DBSCAN聚类
查看>>
Linux设备模型(热插拔、mdev 与 firmware)【转】
查看>>
Android开发笔记第二篇(Android 手机概念)
查看>>
js隐藏与显示回到顶部按钮
查看>>
hdu4496 D-City(扭转和支票托收啊 )
查看>>