Python allows you to open a file, do operations on it, and automatically close it afterwards using with.

>>> with open('/my_path/my_file.txt','r') as f:
>>> file_data = f.read()

In the example above we open a file, perform the operations in the block below the with statement (in this case read from the file) and afterwards Python closes it for us. No need to call

f.close()

In the previous code, the call to f.read() had no arguments passed to it; it defaults to reading all the remainder of the file from its current position - the whole file. If you pass .read() an integer argument, it will read up to that number of characters, output all of them, and keep the 'window' at that position ready to read on.

>>> with open(camelot.txt) as song:
… print(song.read(2))
… print(song.read(8))
… print(song.read())
We
're the
knights of the round table
We dance whenever we're able

Conveniently, Python will loop over the lines of a file using the syntax for line in file. I can use this to create a list of lines in the file. Because each line still has its newline character attached, I remove this using .strip().

>>> camelot_lines = []
>>> with open("camelot.txt") as f:
... for line in f:
... camelot_lines.append(line.strip())
...
>>> print(camelot_lines)
["We're the knights of the round table", "We dance whenever we're able"]

[Python] Working with file的更多相关文章

  1. Python中的file和open简述

    help(file) help(open) 老规矩先看一下内置的帮助文档怎么描述file和open,毕竟官方文档是最直接最准确的描述. Help on class file in module __b ...

  2. Error : Must specify a primary resource (JAR or python or R file)

    spark-submit 报错:must specify resource 取消关注 | 1 ... 我的submit.sh内容: /bin/spark-submit \ --class abc.pa ...

  3. Python load json file with UTF-8 BOM header - Stack Overflow

    Python load json file with UTF-8 BOM header - Stack Overflow 3 down vote Since json.load(stream) use ...

  4. Sublime Text 3 调用cmd运行c、java、python、batch file

    一.调用cmd运行c(首先复制MinGW到C盘根目录,并添加环境变量) Tools --> Build System --> New Build System 删除所有内容 复制如下代码进 ...

  5. python 输入输出,file, os模块

    Python 输入和输出 输出格式美化 Python两种输出值的方式: 表达式语句和 print() 函数. 第三种方式是使用文件对象的 write() 方法,标准输出文件可以用 sys.stdout ...

  6. 调用python脚本报错/usr/bin/env: python : No such file or directory

    一.调用python脚本报错 /usr/bin/env: python: No such file or directory 二.解决方法 原因是在windows上编写的脚本,使用dos2unix对脚 ...

  7. /usr/bin/env python no such file or directory: dos格式导致的!

    最近修改了几个python文件,发现在linux上只能用python file来执行,直接./file提示错误"no such file or directory",而脚本是用&q ...

  8. Python 打开文件(File Open)

    版权所有,未经许可,禁止转载 章节 Python 介绍 Python 开发环境搭建 Python 语法 Python 变量 Python 数值类型 Python 类型转换 Python 字符串(Str ...

  9. 【python】类file文件处理

    [flush方法] 通常由于缓冲,write不将数据写入文件,而是写入内存的缓冲区,需要使用flush写入文件,并清空缓冲区 文件的flush方法的作用是强制清空缓存写入文件.默认每行flush一下? ...

  10. python : No such file or directory

    windows上写的python脚本,在linux上执行时报: No such file or directory 解决方法一# sed -i 's#\r##' mysqlchk.py 解决方法二脚本 ...

随机推荐

  1. Java transientkeyword使用小记

    1. transient的作用及用法 我们都知道一个对象仅仅要实现了Serilizable接口,这个对象就能够被序列化,java的这样的序列化模式为开发人员提供了非常多便利.我们能够不必关系详细序列化 ...

  2. USACO Section 1.3 : Calf Flac (calfflac)

    题意:据说假设你给无限仅仅母牛和无限台巨型便携式电脑(有很大的键盘),那么母牛们会制造出世上最优秀的回文. 你的工作就是去寻找这些牛制造的奇观(最优秀的回文). 在寻找回文时不用理睬那些标点符号.空格 ...

  3. kibana 5.5 源码编译踩坑记录

    由于项目需要定制开发kibana,因此需要编译kibana,在开发环境下运行.   注意:必须下载kibana 5.5的源码才能正常编译,下载release或者snapshot版本是不行的,运行npm ...

  4. 4. idea常用快捷键设置(改为eclipse相似)

    转自:https://blog.csdn.net/loveer0/article/details/82697877 idea常用快捷键设置(改为eclipse相似) 目录 idea常用快捷键设置改为e ...

  5. POJ 1151 线段树+扫描线

    题意:求矩形面积的并 思路: 注意是[l,mid][mid,r] 这是真正的线段了 就当扫描线模板使吧~ //By SiriusRen #include <cmath> #include ...

  6. CUDA学习笔记(四)

    昨天一直在写ben的作业.总结一下周一的cuda情况. cuda程序需要用到一些设置的参数,如argv[],另外cuda读入文件特别苛刻,只能采用C的方式,而且对w+,r的使用只有试通才行. 卧底天外 ...

  7. VS2013+PTVS,python编码问题

    1.调试,input('中文'),乱码2.调试,print('中文'),正常3.不调试,input('中文'),正常4.不调试,print('中文'),正常 页面编码方式已经加了"# -- ...

  8. codeforces 540 B School Marks【贪心】

    题意:一共n个数,给出其中k个数,要求这n个数的中位数为y,这n个数的和不超过x,补全剩下的n-k个数 先统计给出的k个数里面比中位数小的数, 如果cnt<=n/2,说明中位数还没有出现,把这n ...

  9. 外媒分析:iPhone销量低于预期是中国市场疲软影响的

    根据外媒AppleInsider的报道,来自摩根士丹利(Morgan Stanley)的Katy Huberty是最新一位下调苹果目标股价的分析师,她在报告中写道,iPhone的销量低于预期,主要是因 ...

  10. Java基础学习总结(22)——异常处理

    一.异常的概念 异常指的是运行期出现的错误,也就是当程序开始执行以后执行期出现的错误.出现错误时观察错误的名字和行号最为重要. package cn.javastudy.summary; public ...