python基础笔记
路径和文件名不要有中文
#!/usr/bin/env python
#-*- coding:utf-8 -*- 2.7需要加此行。3.5不用
版本区别:
python3.5 print('hello,world') 默认utf-8 input("请输入名字") utf-8转换gbk: decode(''utf8'')先解码成unicode,然后encode("gbk")
python2.7 print 'hello,world' 默认ascii raw_input("请输入名字:") utf-8转换gbk:
单行注释:# ; 多行注释:''' 很多行 '''
.pyc文件:python在执行过程中:python-->字节码-->机器码-->计算机,这个.pyc就是字节码文件,如果把py删掉,pyc也可用
python中的赋值是赋值内存中的地址,a=6;b=a;如果a=7,b仍然是6,因为另外出了个空间装7给a了
continue:跳出当前循环,继续下次循环
break:跳出所有循环
查看对象有哪些方法:
方法1:print(type(temp)),先找到类,然后按住ctrl并在类上面单击
方法2:help(type(temp)) 或dir(temp)
python2.7有的时候不显示文字,而是现实十六进制,这时候需要编码,b=a.decode(''utf8'') ;c=b.encode('gbk')或者x=str(y,encoding='utf-8')
修改自身与创建副本:
一般情况下,字符串的方法多数都是创建副本,list,tuple,dic多数都是修改自身
元组的元素虽然不能变,但tu=(1,2,['a','b'])中的数组是可以变的,其实并不是元组的元素不可以变,只是说元组没有相关的方法。
三元运算:name = 值1 if 条件 else 值2 //如果条件成立,name=值1,如果条件不成立,name=值2
判断一个变量是不是某一个类创建的:
a='hello'
r=isinstance(a,str)
深浅拷贝
一、数字和字符串
对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。
import copy # ######### 数字、字符串 ######### n1 = 123 # n1 = "i am alex age 10" print(id(n1)) # ## 赋值 ## n2 = n1 print(id(n2)) # ## 浅拷贝 ## n2 = copy.copy(n1) print(id(n2)) # ## 深拷贝 ## n3 = copy.deepcopy(n1) print(id(n3))
二、其他基本数据类型
1、赋值,只是创建一个变量,该变量指向原来内存地址,如:
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n2 = n1
2、浅拷贝
浅拷贝,在内存中只额外创建第一层数据
import copy n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n3 = copy.copy(n1)
3、深拷贝
深拷贝,在内存中将所有的数据重新创建一份(除了最后一层,即:python内部对字符串和数字的优化)
import copy n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n4 = copy.deepcopy(n1)
定义函数:
def 函数名(形参): 函数体 return 123
定义函数的时候,如果有含默认值的参数,要把默认值的参数放在后面,例如def email(email,passwd=123)
执行函数:
函数名(实参)
默认实参是与形参一一对应的,如果非不对应,需要在每个实参加上形参,如test(email='xxxx@qq.com',passwd='123')
动态参数一(*arg)表示元组:
def f1(*a): print(a,type(a)) f1(123,456) 显示(123,456),tuple
动态参数二(**arg)表示字典:
def f2(**b): print(b,type(b)) f2(k1=123,k2=456) 返回{k1=123,k2=456},dict
万能参数(*arg,**brg) #注意顺序不能变,*在前,**在后
函数名也可以当作参数来传递
def f1(arg): print(arg) def f2(): print('xxx') f1(f2) #把f2当作参数的话,就没有括号 f2() #执行的话就有括号
内置函数
x=eval("1+2+3") #把字符串作为表达式来执行,eval是有返回值的;结果x=6
x=eval("a+3",{"a":2}) #后面字典是给变量a赋值;结果x=5
exec("for i in range(10):print(i)") #exec也是把字符串作为表达式来执行,只不过exec是没有返回值的
filter(函数名,可迭代的对象):循环可迭代的对象,将迭代的每一个元素作为函数的参数,如果函数值返回True,则保留,否则过滤掉,举例:
def f1(x): if x>2: return True else: return False ret=filter(f1,[1,2,3,4]) #结果ret=[3,4] 注意函数没有括号,这就是把函数当参数
map(函数,可迭代的对象):对每个迭代的对象进行函数运算,返回一个由函数返回值组成的可迭代对象,举例:
ret=map(lambda x:x+100,[1,2,3,4,5]) #结果ret=[101,102,103,104,105]
sort()和sorted()
a=[1,3,2,4] b=sorted(a) #sorted()创建一个副本,a不变 a.sort() #sort()改变自身
文件操作
一、打开文件
open(文件名,模式,编码)
文件句柄 = open('文件路径', '模式') f=open('1.txt','r',encoding='utf-8')默认就是utf-8 data=f.read() 按照utf-8转换成字节 打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。 打开文件的模式有: r ,只读模式【默认】 w,只写模式【不可读;不存在则创建;存在则清空内容;】 x, 只写模式【不可读;不存在则创建,存在则报错】 a, 追加模式【可读; 不存在则创建;存在则只追加内容;】 "+" 表示可以同时读写某个文件 r+, 读写【可读,可写】 w+,写读【可读,可写】 x+ ,写读【可读,可写】 a+, 写读【可读,可写】 "b"表示以字节(二进制)的方式操作,以字节方式打开时不用encoding rb 或 r+b wb 或 w+b xb 或 w+b ab 或 a+b
'r+'(推荐):
如果先读再写,写的时候在末尾追加,指针移动到最后;
如果想在某一位置写,要先f.seek(位置号)再写,会覆盖后面的(用f.tell()查看当前位置)
’w+':打开的同时已经清空,再写入之后,才能读,并且需要调整指针f.seek(0)才能读出来,要不然指针在最后
‘a+':打开的同时指针已经到最后,写的时候也是追加,指针到最后,就算seek,也是最后
二、操作文件
for line in f: print(line) f自带可迭代每行 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 for further I/O operations. close() may be called more than once without error. 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. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判断文件是否是同意tty设备 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 获取下一行数据,不存在,则报错 """ x.next() -> the next value, or raise StopIteration """ pass def 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 requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 读取到缓冲区,不要用,将被遗弃 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def 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 maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def 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 the total 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 (move relative to end of file, usually negative, although many platforms allow seeking 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 causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 获取当前指针位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def 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(). """ pass def 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 before the file on disk reflects the data written. """ pass def 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 object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用于逐行读取文件,非全部 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass
class TextIOWrapper(_TextIOBase): """ Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see help(codecs.Codec) or the documentation for codecs.register) and defaults to "strict". newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If line_buffering is True, a call to flush is implied when a call to write contains a newline character. """ def close(self, *args, **kwargs): # real signature unknown 关闭文件 pass def fileno(self, *args, **kwargs): # real signature unknown 文件描述符 pass def flush(self, *args, **kwargs): # real signature unknown 刷新文件内部缓冲区 pass def isatty(self, *args, **kwargs): # real signature unknown 判断文件是否是同意tty设备 pass def read(self, *args, **kwargs): # real signature unknown 读取指定字节数据 pass def readable(self, *args, **kwargs): # real signature unknown 是否可读 pass def readline(self, *args, **kwargs): # real signature unknown 仅读取一行数据 pass def seek(self, *args, **kwargs): # real signature unknown 指定文件中指针位置 pass def seekable(self, *args, **kwargs): # real signature unknown 指针是否可操作 pass def tell(self, *args, **kwargs): # real signature unknown 获取指针位置 pass def truncate(self, *args, **kwargs): # real signature unknown 截断数据,仅保留指定之前数据 pass def writable(self, *args, **kwargs): # real signature unknown 是否可写 pass def write(self, *args, **kwargs): # real signature unknown 写内容 pass def __getstate__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __next__(self, *args, **kwargs): # real signature unknown """ Implement next(self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
with open('a.txt','r') as f: f.read() #省去了f.close()
同时打开两个文件:
with open('a.txt','r') as f1,open('b.txt','r') as f2