Python File I/O
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following order.
Open a file
Read or write (perform operation)
Close the file
Opening a File
Python has a built-in function open()
to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
>>> f =
open("test.txt") # open file in current directory
>>> f =
open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode. The default is reading in text mode. In this mode, we get strings when reading from the file. On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
Python File Modes
Mode |
Description |
---|---|
'r' |
Open a file for reading. (default) |
'w' |
Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. |
'x' |
Open a file for exclusive creation. If the file already exists, the operation fails. |
'a' |
Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. |
't' |
Open in text mode. (default) |
'b' |
Open in binary mode. |
'+' |
Open a file for updating (reading and writing) |
f = open("test.txt")
# equivalent to 'r' or 'rt'
f = open("test.txt",'w')
# write in text mode
f = open("img.bmp",'r+b')
# read and write in binary mode
Since the version 3.x, Python has made a clear distinction between str
(text) and bytes
(8-bits). Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII
(or other equivalent encodings). Hence, when working with files in text mode, it is recommended to specify the encoding type. Files are stored in bytes in the disk, we need to decode them into str
when we read into Python. Similarly, encoding is performed while writing texts to the file.
The default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in Linux. Hence, we must not rely on the default encoding otherwise, our code will behave differently in different platforms. Thus, this is the preferred way to open a file for reading in text mode.
f
= open("test.txt",mode = 'r',encoding = 'utf-8')
Closing a File
When we are done with operations to the file, we need to properly close it. Python has a garbage collector to clean up unreferenced objects. But we must not rely on it to close the file. Closing a file will free up the resources that were tied with the file and is done using the close()
method.
f =
open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file. A safer way is to use a try...finally
block.
try:
f
= open("test.txt",encoding = 'utf-8')
#
perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing program flow to stop.
The best way to do this is using the with
statement. This ensures that the file is closed when the block inside with
is exited. We don't need to explicitly call the close()
method. It is done internally.
with
open("test.txt",encoding = 'utf-8') as f:
#
perform file operations
Writing to a File
In order to write into a file we need to open it in write 'w', append 'a' or exclusive creation 'x' mode. We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write()
method. This method returns the number of characters written to the file.
with
open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my
first file\n")
f.write("This
file\n\n")
f.write("contains
three lines\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is overwritten. We must include the newline characters ourselves to distinguish different lines.
Reading From a File
To read the content of a file, we must open the file in reading mode. There are various methods available for this purpose. We can use the read(size)
method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.
>>> f =
open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4)
# read the first 4 data
'This'
>>> f.read(4)
# read the next 4 data
' is '
>>> f.read()
# read in the rest till end of file
'my first file\nThis
file\ncontains three lines\n'
>>> f.read() #
further reading returns empty sting
''
We can see, that read()
method returns newline as '\n'. Once the end of file is reached, we get empty string on further reading. We can change our current file cursor (position) using the seek()
method. Similarly, the tell()
method returns our current position (in number of bytes).
>>> f.tell()
# get the current file position
>>> f.seek(0)
# bring file cursor to initial position
>>>
print(f.read()) # read the entire file
This is my first file
This file
contains three lines
We can read a file line-by-line using a for
loop. This is both efficient and fast.
>>> for line in
f:
... print(line, end =
'')
...
This is my first file
This file
contains three lines
The lines in file itself has a newline character '\n'. Moreover,the print()
function also appends a newline by default. Hence, we specify the end parameter to avoid two newlines when printing.
Alternately, we can use readline()
method to read individual lines of a file. This method reads a file till the newline, including the newline character.
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines()
method returns a list of remaining lines of the entire file. All these reading method return empty values when end of file (EOF) is reached.
>>>
f.readlines()
['This is my first
file\n', 'This file\n', 'contains three lines\n']
Python File Methods
There are various methods available with the file object. Some of them have been used in above examples. Here is the complete list of methods in text mode with a brief description.
Python File Methods
Python File I/O的更多相关文章
- Python - File - 第十八天
Python File(文件) 方法 open() 方法 Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OS ...
- [转]python file文件操作--内置对象open
python file文件操作--内置对象open 说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...
- Python & file operation mode
Python & file operation mode create/read/write/append mode https://docs.python.org/3/library/fun ...
- [python] File path and system path
1. get files in the current directory with the assum that the directory is like this: a .py |----dat ...
- python file operations
原文地址 总是记不住API.昨晚写的时候用到了这些,但是没记住,于是就索性整理一下吧: python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当 ...
- python file 文件读写
python 文本对象 继承自C的stdio包 打开 可以用内置的open()函数创建 with open("hello.txt") as f: for line in f: pr ...
- python file模块 替换输入内容脚本
root@python-10:/home/liujianzuo/python/test# ls passwd rc.local test1 root@python-10:/home/liujianzu ...
- python file operation
file.open(name[,mode[,buffering]]) 模式的类型有: r 默认只读 w 以写方式打开,如果文件不存在则会先创建,如果文件存在则先把文件内容清空(truncate ...
- python file文件操作--内置对象open
说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前工作目录)或者一个绝对路径,当传入路径不存在此文件会报错 ...
随机推荐
- bzoj题解汇总(1021~1031)
bzoj1021:普通dp bzoj1022:裸的Anti-Nim 必胜:①sg=0且所有不超过1 ②sg>1且存在至少一个超过1 bzoj1023:http://www.cnblogs.com ...
- jQuery与DOM相互转换
先执行一下代码 $(function () { var div=$("<div></div>"); console.log(div); }); (注意,di ...
- 3.5 EF Code First总结
1. 主键约定 属性名为“ID”(不区分大小写)或类名的后面跟有“ID”. 2. 关系约定 模型之间的关系,EF根据针对类型定义的导航属性来推断关系. 3. 连接字符串约定 (1)默认配置 如果连接字 ...
- NOR FLASH与NAND FLASH的区别
NOR和NAND是现在市场上两种主要的非易失闪存技术.Intel于1988年首先开发出NOR flash技术,彻底改变了原先由EPROM和EEPROM一统天下的局面.紧接着,1989年,东芝公司发表了 ...
- 201. Bitwise AND of Numbers Range -- 连续整数按位与的和
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers ...
- Tomcat数据库连接池的配置方法总结
Tomcat数据库连接池的配置方法总结 数据库连接是一种关键的有限的昂贵的资源,这在多用户网页应用程序中体现的尤为突出.对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标 ...
- 修改Linux系统时区
修改配置文件来修改时区1.修改/etc/sysconfig/clock ZONE=Asia/Shanghai 2.rm /etc/localtime3.链接到上海时区文件 ln -sf ...
- JavaScript中的test()方法
定义和用法 test() 方法用于检测一个字符串是否匹配某个模式. 语法 RegExpObject.test(string) 参数 描述 string 必需.要检测的字符串. 返回值 如果字符串 st ...
- SQL Server之字符串函数
以下所有例子均Studnet表为例: 计算字符串长度len()用来计算字符串的长度 select sname ,len(sname) from student 字符串转换为大.小写lower() ...
- oracle Redhat64 安装错误3
问题描述 /usr/bin/ld: cannot find -lxxx 其中xxx即表示函式库文件名称,其命名规则是:lib+库名(即xxx)+.so. 可能原因: 1 安装了,但相对应的lib版本 ...