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. css实现上下左右布局

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  2. python 3.x 写 shell sed 替换功能

    shell sed 替换功能 f1 = open('yesterday','r',encoding='utf-8') f2 = open('yesterday2','w',encoding='utf- ...

  3. Spring控制反转容器的使用例子

    详细代码如下: spring-config.xml <?xml version="1.0" encoding="UTF-8"?> <beans ...

  4. PostgreSQL Replication之第八章 与pgbouncer一起工作(2)

    8.2 安装pgbouncer 在我们深入细节之前,我们将看看如何安装pgbouncer.正如PostgreSQL一样,您可以采取两种途径.您可以安装二进制包或者直接从源代码编译.在我们的例子中,我们 ...

  5. hdu 3292 No more tricks, Mr Nanguo

    No more tricks, Mr Nanguo Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Jav ...

  6. 51Nod 不重叠的线段(贪心)

    X轴上有N条线段,每条线段有1个起点S和终点E.最多能够选出多少条互不重叠的线段.(注:起点或终点重叠,不算重叠). 例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重 ...

  7. 求第区间第k大数 TLE归并树

    题 给定N个正整数构成的序列,将对于指定的闭区间查询其区间内的第K小值. 输入: 第一行包含两个正整数N.M,分别表示序列的长度和查询的个数. 第二行包含N个正整数,表示这个序列各项的数字. 接下来M ...

  8. 网页加速之Chromium 预载入 Prerendering

    前一篇博文已经介绍通过prefetch预先载入网页的资源来提升网页载入速度,以下我们一起来看一下网页加速之chromium prerendering.在介绍prerendering之前,先介绍两个概念 ...

  9. UMeditor百度富文本编辑器的使用

    批量上传的图片在线管理没法查看图片 是因为jar包本身的Bug,这里暂时做了个替换展示.就是找到Img.js  然后搜索 img.set 替换下就好了 var url=list[i].url ;    ...

  10. scikit-learn的线性回归

    scikit-learn的线性回归预测Google股票 这是机器学习系列的第一篇文章. 本文将使用Python及scikit-learn的线性回归预测Google的股票走势.请千万别期望这个示例能够让 ...