博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python文件基本操作
阅读量:4610 次
发布时间:2019-06-09

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

1、open()与read()

  open():打开文件;read():读取文件。

with open('a.txt', 'r') as f:    data = f.read()    print(data)    print("file encoding:",f.encoding)

  打印输出结果:

end actionend actionend action2016-08-06 17:08:23 end action2016-08-06 17:08:23 end action2016-08-06 17:08:23 end actionfile encoding: cp936

  f.encoding输出文件的编码格式。

2、write()、flush()与close()

  write():写文件;

  flush():刷新缓冲区

  close():关闭文件

2.1、爬取https://www.baidu.com的数据并保存

  注意:response.text的编码格式保存在response.encoding中,可以打印出来,打开baidu.txt文件时编码格式要与其一致,否则保存的是乱码。

import requestsresponse = requests.get('https://www.baidu.com')# print(response.headers)print(type(response.text))print(response.text.encode("ISO-8859-1").decode("utf-8"))print(response.encoding)f = open('baidu.txt', 'w',encoding='ISO-8859-1')f.write(response.text)f.flush()f.close()

2.2、读取保存的数据并显示

# 读取保存的数据并显示with open('baidu.txt', 'r',encoding='utf-8') as f:    data = f.read()    print(data)    print("file encoding:",f.encoding)

  打印输出结果:

百度一下,你就知道

关于百度 About Baidu

©2017 Baidu 使用百度前必读  意见反馈 京ICP证030173号 

file encoding: utf-8

3、循环读取文件

f = open('baidu.txt','r', encoding='utf-8')count = 0for line in f:    if count == 3:        print("--------我是分割线----------")        count += 1        continue    print(line)    count += 1

4、readline()

4.1、用于从文件读取整行,包括 "\n" 字符。

f = open('baidu.txt','r', encoding='utf-8')for i in range(5):    print(f.readline())f.close()

4.2、从文件中读取指定字节长度的数据

f = open('baidu.txt','r', encoding='utf-8')data = f.readline(10)print(data)data2 = f.readline(10)print(data2)f.close()

  打印输出结果:

 

5、文件修改

  将文件中"我"替换成"你",并写入新的文件。

import sysfind_str = "我"replace_str = "你"with open("yesterday2", "r", encoding="utf-8") as f,\    open("yesterday2.bak", "w",encoding="utf-8") as f_new:        print("old:\n",f.readlines())        f.seek(0) # 移动文件指针        for line in f:            if find_str in line:                                line = line.replace(find_str, replace_str)            f_new.write(line)        f_new.flush()print("*"*50)with open("yesterday2.bak", "r",encoding="utf-8") as f_new:    print("new:\n",f_new.readlines())

  打印输出结果:

old: ['Oh, yesterday when I was young\n', '噢 昨日当我年少轻狂\n', 'So many, many songs were waiting to be sung\n', '有那么那么多甜美的曲儿等我歌唱\n', 'So many wild pleasures lay in store for me\n', '有那么多肆意的快乐等我享受\n', 'And so much pain my eyes refused to see\n', '还有那么多痛苦 我的双眼却视而不见\n', "There are so many songs in me that won't be sung\n", '我有太多歌曲永远不会被唱起\n', 'I feel the bitter taste of tears upon my tongue\n', '我尝到了舌尖泪水的苦涩滋味\n', 'The time has come for me to pay for yesterday\n', '终于到了付出代价的时间 为了昨日\n', 'When I was young\n', '当我年少轻狂\n']**************************************************new: ['Oh, yesterday when I was young\n', '噢 昨日当你年少轻狂\n', 'So many, many songs were waiting to be sung\n', '有那么那么多甜美的曲儿等你歌唱\n', 'So many wild pleasures lay in store for me\n', '有那么多肆意的快乐等你享受\n', 'And so much pain my eyes refused to see\n', '还有那么多痛苦 你的双眼却视而不见\n', "There are so many songs in me that won't be sung\n", '你有太多歌曲永远不会被唱起\n', 'I feel the bitter taste of tears upon my tongue\n', '你尝到了舌尖泪水的苦涩滋味\n', 'The time has come for me to pay for yesterday\n', '终于到了付出代价的时间 为了昨日\n', 'When I was young\n', '当你年少轻狂\n']

 

转载于:https://www.cnblogs.com/bad-robot/p/9678993.html

你可能感兴趣的文章
Git的安装和使用教程详解
查看>>
lsof命令详解
查看>>
常用模块,异常处理
查看>>
父窗口与子窗口之间的传值
查看>>
eclipse 找不到 tomcat 的解决方案
查看>>
HDU 1890--Robotic Sort(Splay Tree)
查看>>
connection string for Excel/Access 2010
查看>>
【转】【Python】Python中的__init__.py与模块导入(from import 找不到模块的问题)
查看>>
学习wavenet_vocoder之环境配置
查看>>
常用Maven命令
查看>>
Docker启动mysql的坑2
查看>>
j2ee爬坑行之二 servlet
查看>>
JAVA基础入门(JDK、eclipse下载安装)
查看>>
最基础的applet运用--在applet上画线
查看>>
布局大全
查看>>
eclipse中安装tomcat插件
查看>>
常见设计模式C++代码实现
查看>>
C++线程同步的四种方式(Windows)
查看>>
前端面试集锦(1)
查看>>
What are Upgrade, Product and Package Codes used for? By pusu
查看>>