大学网站建设评比考核办法,淘宝网店运营培训,wordpress排版代码,修改wordpress编辑器文章目录1.打开文件2.文件读取3.文件关闭4.文件写入/追加1.打开文件
当传参顺序不一致时#xff0c;不能使用位置传参#xff0c;应使用关键字传参 open(file, mode‘r’, buffering-1, encodingNone, errorsNone, newlineNone, closefdTrue, openerNone)
通常使用#xf…
文章目录1.打开文件2.文件读取3.文件关闭4.文件写入/追加1.打开文件
当传参顺序不一致时不能使用位置传参应使用关键字传参 open(file, mode‘r’, buffering-1, encodingNone, errorsNone, newlineNone, closefdTrue, openerNone)
通常使用 open(file“”,mode“”,encoding“”) 1file(所在路径)文件名 2mode打开文件的模式 ①只读r默认模式可省略 ②写入w若原文件存在会删除原文件的内容重新开始编辑如果文件不存在会创建新文件 ③追加a原文件内容不会被删除可以在后面写入新的内容如果文件不存在会创建新文件 3encoding编码格式 默认为UTF-8某些情况下可省略但建议注明。常见的编码有UTF-8、GBK、Big5
2.文件读取
1read(num)方法从文件中读取指定字节num的数据如果num为空默认全部读入
例如在D盘有一个hello.txt的文件 打开并读取 如果多次使用read(num)会从上次读取结束的位置继续往后读取num个字节如果上次已经读到底再调用read将读不到任何数据
fopen(fileD:/hello.txt,moder,encodingUTF-8)
print(f.read())2readlines()按照行的方式把整个文件中的内容进行一次性读取返回一个列表其中每一行的数据为一个元素 fopen(fileD:/hello.txt,moder,encodingUTF-8)
print(f.readlines())3readline()方法调用一次只会读取到一行
fopen(fileD:/hello.txt,moder,encodingUTF-8)
print(f.readline())
print(f.readline())
print(f.readline())4使用for循环读取 每次调用都会读取一行的内容
fopen(fileD:/hello.txt,moder,encodingUTF-8)
for x in f:print(x)3.文件关闭
使用结束后使用close关闭文件对象结束对文件的占用 如果不使用close文件会在程序结束运行时关闭 文件未关闭时相当于文件已打开不能在计算机上对文件进行删除、重命名等操作
fopen(fileD:/hello.txt,moder,encodingUTF-8)
f.close()
print(f.read()) # ValueError: I/O operation on closed file.操作完成后自动关闭文件 with open不再需要close操作
with open(fileD:/hello.txt,moder,encodingUTF-8) as f:print(f.read()) # 输出见下图
print(f.read()) # ValueError: I/O operation on closed file.[练习] 统计D:/practice.txt下图中单词and出现的次数 [解] 法一使用read读取count计数
fopen(D:/practice.txt,r)
print(f.read().count(and))
f.close()输出11 此方法统计的是文中出现and”的次数而非and”单词的数量 法二使用for循环读取 此方法能准确统计到and”单词出现的次数
count0 # 记录单词and出现的次数
fopen(D:/practice.txt,r)
for x in f: # 每次读取一行xx.strip() # 去除开头和结尾的空格和换行符wordsx.split( ) # 以空格切割字符串形成一个个单词存入wordsfor y in words:if yand:count1
print(count)输出10
4.文件写入/追加
f.write(“写入内容”)写入内存缓冲区 f.flush()真正写入文件追加需要写入不需要 1追加
fopen(D:/hello.txt,a) # 追加打开不可读
f.write(nihao)
f.flush() # 必须有
f.close()追加打开不可读需要重新只读读打开
fopen(D:/hello.txt,a) # 追加打开不可读
f.write(nihao)
f.flush()
print(f.read()) # io.UnsupportedOperation: not readablefopen(D:/hello.txt,a) # 追加打开不可读
f.write(nihao)
f.flush()
fopen(D:/hello.txt,r) # 只读
print(f.read()) # hahanihao换行追加 fopen(D:/newfile.txt,a)
f.write(\nhello)
f.close()2写入 写入可以不使用flush会自动调用
D盘无文件
fopen(D:/newfile.txt,w) # 创建新文件newfile.txt
f.write(newwrite)
f.close()在此基础上覆盖写入
fopen(D:/newfile.txt,w)
f.write(nihao)
f.close()同样写入操作也不能读取
[练习] 将D盘下test.txt文件的内容的正式项拷贝到D盘下bill.txt的文件中 foldopen(D:/test.txt,r,encodingUTF-8) # 老文件用fold标识只读即可
fnewopen(D:/bill.txt,w,encodingUTF-8) # 新文件用fnew标识这里用的是写入w
for x in fold: # 遍历每一行xx.strip()if x.split(,)[3] 测试: # 分割结果用列表保存可以进行下标索引continue
# 等价于 wordx.split(,); if word[3]...fnew.write(x\n)
fold.close()
fnew.close()