Python学习笔记——文件

时间:2023-03-09 18:52:59
Python学习笔记——文件
1、文件只是连续的字节序列
open()内建函数是打开文件之门的钥匙
file_obj=open(file_name,access_mode='r/w/a,' buffering=-1)
file_name是要打开的文件名,可以是相对路径或者绝对路径。
assess_mode代表打开文件的模式,r表示只读,w表示写入,a表示追加。还有一个U模式,代表通用换行支持
使用r和U的文件必须存在,使用W模式打开文件若存在则首先清空,然后重新创建。‘a’模式写入的数据全部都追加到问价的末尾。还有‘+’表示可读可写,‘b’表示二进制方式访问
buffering用于指示访问文件所采用的缓冲方式:0表示不缓冲,1表示只缓冲一行,任何其他大于1的值表示使用给定的值作为缓冲器的大小
2、文件的内建函数:
(1)、输入:
read()方法用来直接读取字节到字符串中,最多读取给定数目个字节。如果没有给定size,则读取到末尾。
readline()方法读取打开文件的一行,然后整行(包括行结束符)输出。
readlines():会读取所有的(剩余的行)行然后把它们作为一个字符串列表返回
(2)输出
write()方法
writelines()方法是针对列表的操作,接受一个字符串作为参数,把它们写进文件
核心笔记:保留行分隔符:
在使用read和readlines从文件中读取行,python并不会删除行分隔符,因此这个操作留给了程序员;常见程序:
f=open('my.txt','r')
data=[line.strip() for line in f.readlines()]
f.close()
类似的,write和writelines()也应该有用户自己处理
(3)文件内移动:
seek()方法。text()方法。
(4)文件迭代:
for eachLine i f:。。。。
(5)close()方法关闭对文件的访问
注意:print语句默认在输出内容末尾加一个换行符,加一个逗号就可以解决这个问题。
3、命令行参数:是调用某个程序时除程序名以外的其他参数。sys模块通过sys.argv属性对命令行参数访问。
sys.argv是命令行参数的列表
len(sys.argv)是命令行参数的个数(argc)
4、文件系统:
对文件系统的访问大多通过Python的os模块实现。该模块是Python访问操作系统功能的主要接口。
例子:os和os.path模块的例子
import os
for tempdir in ('/tmp',r'c:\temp'):
if os.path.isdir(tempdir):
break
else:
print ('no temp directory available')
tempdir=''
if tempdir:
os.chdir(tempdir)
cwd=os.getcwd()
print ('****current temporary directory:')
print (cwd) print('****creating example directory:')
os.mkdir('example')
os.chdir('example')
cwd=os.getcwd()
print ('****new working directory:')
print (cwd)
print("****original directory listing:")
print(os.listdir(cwd))
print ('****creating test file...')
f=open('test','w')
f.write('foo\n')
f.write('bar\n')
f.close()
print('****updated directory listing:')
print(os.listdir(cwd)) print("****renaming 'test'to'filetest.txt'")
os.rename('test','filetest. txt')
print ('****updated directory listing:')
print (os.listdir(cwd)) path=os.path.join(cwd,os.listdir(cwd)[0])
print ('****full file pathname:')
print (path)
print('****(pathname,basename) == ')
print (os.path.split(path))
print ('****(filename,extension)==')
print (os.path.splitext(os.path.basename(path))) print ('****displaying file contents:')
f=open(path)
for eachLine in f:
print(eachLine)
f.close() print ("****deleting test file")
os.remove(path)
print ('****updated directory listing:')
print (os.listdir(cwd))
os.chdir(os.pardir)
print ('****deleting test directory')
os.rmdir('example')
print('****Done')