打开文件file_handler = open(filename,mode)
Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.
The first two arguments are the same as for stdio‘s fopen: filename is the file name to be opened, and mode is a string indicating how the file is to be opened.
The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.
The optional bufsize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. [2]
Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.
In addition to the standard fopen values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.
Python enforces that the mode, after stripping 'U', begins with 'r', 'w' or 'a'.
Python provides many file handling modules including fileinput, os, os.path, tempfile, and shutil.
Changed in version 2.5: Restriction on first letter of mode string introduced.
mode:
r 只读
w 写,覆盖已有内容。
a 追加模式,如果文件不存在则创建
r+ 读写
w+ 消除文件内容,然后以读写方式打开文件。
a+ 读写方式,并把文件指针移到文件尾。
b 二进制模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。
读取文件内容
File Objects
File objects are implemented using C’s stdio package and can be created with the built-in open() function. File objects are also returned by some other built-in functions and methods, such as os.popen() and os.fdopen() and the makefile() method of socket objects. Temporary files can be created using the tempfile module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.
When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.
f.read([count]) 读出文件,如果有count,则读出count个字节。Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.
f.readline() 读出一行信息。
f.readlines()读出所有行,也就是读出整个文件的信息。写入文件内容
f.write(string)把string字符串写入文件。
f.writelines(list) 把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。
换行符在各个操作系统中界定的不同,Windows换行符是‘\r\n',Unix/Linux的换行符为'\n',Mac的换行符为'\r';
在python中,对换行符进行了统一处理,定义为'\n',以文本模式写入时,如果是Windows系统,则python会自动将\n转为\r\n,Mac系统类似;
文件指针操作
f.seek(offset[,where]) 把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。
f.tell()获得文件指针位置。
文件信息操作
f.fileno()获得文件描述符,是一个数字. Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the fcntl module or os.read() and friends.
f.isatty()如果文件是一个交互终端,则返回True,否则返回False。
其他
f.close()
f.flush(): Flush the internal buffer, like stdio‘s fflush. This may be a no-op on some file-like objects.
f.truncate([size]) 截取文件,使文件的大小为size。
举例:
打印当前文件目录 data文件夹下的所有文件
import os procPath=os.getcwd() dataPath=procPath+"/data" files=[files for files in os.listdir(dataPath) ] #if (files.find(timestamp) != -1)] print files
基本读写
#!/usr/bin/env python # -*- coding: gb18030 -*- poem='''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' #1. write file f=open('poem.txt', 'w') #open for 'w'riting f.write(poem) #write text to file f.close() #close the file #2. read file f=open('poem.txt') #if no mode is specified, 'r'ead mode is assumed by default while True: line=f.readline() if len(line) == 0: #Zero length indicates EOF #此时line=="" break print line, #notice comma to avoid automatic newline f.close() #close the file #3. append file f=open('poem.txt','a') f.write('hehe') f.write("haha") f.close()
按行读写
#!/usr/bin/env python # -*- coding: gb18030 -*- ''' 本文件说明: 1. “list”遍历 for ind in range(0,len(sample_list), 1): sample_list[ind] #这样可以得到下标 ... 或 for ele in sample_list ele #这样也行,但不能得到下标 ... 2. “Python类型判断”: type(ele) is types.IntType 和 type(ele) == types.StringType是等价的—— (1) type的返回值是一个"类",types.IntType也是一个"类" (2) is 比较的是是否指向同一个对象; == 比较的是类型的值 3. “Python类型转换”: int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 complex(real [,imag ]) 创建一个复数 str(x ) 将对象 x 转换为字符串 ; 转为字符串也可以类似这样做 "%d" %int_var repr(x ) 将对象 x 转换为表达式字符串 eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象 tuple(s ) 将序列 s 转换为一个元组 list(s ) 将序列 s 转换为一个列表 chr(x ) 将一个整数转换为一个字符 unichr(x ) 将一个整数转换为Unicode字符 ord(x ) 将一个字符转换为它的整数值 hex(x ) 将一个整数转换为一个十六进制字符串 oct(x ) 将一个整数转换为一个八进制字符串 4. 字符串变量 和 字符串常量 不同: 字符串变量 在“拼接”时,需要加上“+” i.e. str_var+"hehe" 字符串常量 在“拼接”时,直接拼接 i.e. "sam""hehe" 5. 按行写入文件 ''' import types sample_list=['hehe',"Haha",3,"哈哈","Hey\\Hey","三木!"] for ind in range(0,len(sample_list),1): if type(sample_list[ind]) is types.IntType: #类型判断 #sample_list[ind]=("%d\n" %sample_list[ind]) #int变量转字符串需要这样: "%d" %i sample_list[ind]=str(sample_list[ind])+"\n" #字符串变量+字符串常量 elif type(sample_list[ind]) is types.StringType: sample_list[ind]=(sample_list[ind]+"\n") #字符串变量+字符串常量 else: pass #观察打印出list和list[i]的区别,体会print的功能 print print sample_list print sample_list[3] #按行写入文件 f=open('myFile.txt','a') f.writelines(sample_list) #writelines(list)是不会自动加上换行符的 f.close()
相关推荐
新建 Python File.py
Simple Python style checker in one Python file
file.py
please refer to this website for more details: https://www.runoob.com/python/file-seek.html
readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理。 如果碰到结束符 EOF 则返回空字符串。 语法 readlines() 方法语法如下: fileObject.readlines( );...
【Python File Monitor 开源项目详解】 Python File Monitor是一款基于Python编写的开源监控工具,它能够实时监测指定文件或目录的变化,并在检测到变化时执行预设的命令。这个工具适用于那些需要在文件系统变动时...
【标题】"FileBrowser_python_browser_" 是一个基于Python编写的文件浏览器应用,旨在实现一个简易的文件网站。这个小作业的目的是让学生通过编程实践理解网络通信的基本原理,并掌握如何利用Python构建一个本地文件...
一个简简单单的小程序
Python库file_storage-0.1.6-py3-none-any.whl是一个用于数据存储和管理的模块,专为Python开发人员设计。这个压缩包文件是一个wheel格式的软件包,它是Python社区广泛接受的一种预编译的包分发格式,允许用户快速...
### Python 文件操作详解 #### 一、引言 在Python编程中,文件操作是一项非常基础且重要的技能。无论是处理文本数据、配置文件还是其他类型的文件,掌握如何有效地打开、读取、写入以及关闭文件都是必不可少的能力...
本文将深入探讨`as.recipe.filetemplate-2.2.0-py2.7.egg`这个特定的Python库,它主要用于构建和管理文件模板。这个库的名字表明它是`as`组织的一部分,并且是`recipe`系列的一个组件,专注于处理`filetemplate`。...
$ python file-server.py files 8001 其中第一个参数 files 是存放文件的路径,第二个参数 8001 是 HTTP 服务器端口。 接口 1. 读取文件 GET /pathtofile/filename 2. 读取文件夹下所有文件(已经忽略隐藏文件) GET...
资源分类:Python库 所属语言:Python 使用前提:需要解压 资源全名:filedate-1.4-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
file.write('Hello, Python!') file.close() ``` 追加内容则使用'a'模式: ```python file = open('src/newfile.txt', 'a') file.write('\n appending some text') file.close() ``` 除了基本的读写,还有其他高级...
zheshfiafjdsioafjsafdklsafafasfdskalfjsaklfsadfasd
本文主要讲解Python中读写文件以及file对象的相关方法。 首先,当我们使用`open()`函数打开一个文件时,必须确保在使用完毕后调用`close()`方法关闭文件,以释放系统资源。为了确保文件总能被正确关闭,通常建议...
在Python编程语言中,查找和删除文件是两个常见的文件系统操作。`find file and del`这个主题涵盖了如何在文件系统中搜索特定文件以及在找到后如何安全地删除它们。下面将详细讲解这两个方面。 首先,让我们关注...
python 启动器,解决执行py.exe启动时的问题 Python Launcher for python2 and python3 CSDN-tags: py.exe default python ...pythonfile.bat用于导出Python的注册表信息备份,重装系统或是纠错(我更喜欢看文本)。