Python 文件和输入输出小结
1.打开和关闭文件(open(),file(),close())
有两种内建函数可以获取文件对象:open和file。他们的用法完全一样。下面只以open()为例子讲解。获取一个文件对象(打开文件)的语法如下:
代码如下:
fileObj = open(filename,access_mode='r',buffering=-1)
filename不用说你也应该知道是你要打开文件的路径。
access_mode用来标识文件打开的模式,默认为r(只读)。
常用的模式如下表所示:
文件模式 | 解释 |
r | 以只读方式打开 |
w | 以写方式打开,文件不为空时清空文件;文件不存在时新建文件。 |
a | 追加模式,没有则创建 |
r+,w+,a+ | 以读写模式打开,参见w,a |
另外还有一个b表示二进制模式访问,但是对于Linux或者unix系统来说这个模式没有任何意义,因为他们把所有文件都看作二进制文件,包括文本文件。
第三个参数不经常用到,标识访问文件的缓冲方式,0代表不缓冲,1代表缓
冲一行,-1代表使用系统默认缓冲方式。只要使用系统默认就好。
一些例子:
代码如下:
>>> f = open('/etc/passwd','r')
>>> f1 = open('/etc/test','w')
使用完文件后,一定要记得关闭文件,操作如下:
代码如下:
>>> f.close()
2.文件读入
2.1.file.read(size = -1)
读取从当前文件游标起size个字节的文件内容。如果size=-1,则读取所有剩余字节。
代码如下:
>>> f = open('/etc/passwd')
>>> f.read(100)
'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nol'
2.2.file.readlines(size=-1)
从文件中读取并返回一行(包括行结束符),或返回最大size个字符
代码如下:
>>> f.readline()
'ogin\n'#和上面一个例子输出的最后拼起来就是 'nologin',因为游标在l后面。
>>> f.readline(1)
'a'
2.3.file.readlines(sizhint=0)
读取文件所有的行,并作为一个列表返回(包括行结束符),如果sizhint>0则返回总和大约sizhint字节的行(具体由缓冲区大小决定)。
代码如下:
f.readlines()
['dm:x:3:4:adm:/var/adm:/sbin/nologin\n', 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n', 'sync:x:5:0:sync:/sbin:/bin/sync\n', 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n', 'halt:x:7:0:halt:/sbin:/sbin/halt\n', 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n', ......
输出省略。
3.文件输出
3.1.file.write(str)
向文件中写入指定的字符串。
代码如下:
>>> f = file('/root/test.py','w+')
>>> f.write("print 'hello,world'")
>>> f.read()
''
>>> f.close()
>>> file('/root/test.py','r').read()
"print 'hello,world'"
3.2.file.write(seq)
向文件写入字符串序列seq。seq是任何返回字符串的可迭代对象。
代码如下:
>>> f = file('/root/test.py','a+')
>>> codelst = ['\n','import os\n',"os.popen('ls').read()\n"]
>>> f.writelines(codelst)
>>> f.close()
>>> file('/root/test.py','r').read()
"print 'hello,world'\nimport os\nos.popen('ls').read()\n"
注意,文件写入的时候,不会自动加上换行符,必须手动加上。
4.文件移动
学过C语言的同学,一定对fseek()函数不陌生,在Python中,seek()方法是fseek()的替代者。
seek(offset,whence=0)
方法可以将文件游标移动到文件的任意位置。其中offset代表需要移动的偏移字节数,whence表示要从哪个位置开始偏移:
0代表从文件开头开始算起,
1代表从当前位置开始算起,
2代表从文件末尾算起。
那我们如何知道当前文件游标在哪里呢?别担心,这里有个tell()方法可以返回当前文件游标的位置。
5.文件迭代
在Python中,文件不仅仅是一个对象,而且是一个可迭代对象!我们可以利用如下迭代方式,轻松的访问和处理文件内容,而不必全部读出(readlines)后再迭代(性能上差了很多哦!)
代码如下:
for eachline in f:
#dealwith eachline of f
例如:
代码如下:
>>> for eachline in f:
... print eachline
6.os、os.path与文件
os和os.path中提供了一些跟文件有关的接口,下面介绍一些常用的接口。其他接口可以自己查阅相关文档。
注意:以下函数传入的参数都是字符串形式的文件名字,文件名可由文件对象的name属性获得。
函数 | 描述 |
os.path.basename() | 去掉目录路径,返回文件名 |
os.path.dirname() | 去掉文件名,返回目录路径 |
os.path.getatime() os.path.getctime() os.path.getmtime() os.path.size() |
返回文件的atime,ctime,mtime和大小 |
os.path.exists() | 该文件或目录是否存在 |
os.path.abs() | 指定路径是否为绝对路径 |
os.path.isdir() | 路径是否存在且为目录 |
os.path.isfile() | 路径是否存在且为文件。 |
os.path.islink() | 指定路径是否存在且为一个符号链接 |
代码如下:
>>> import os.path
>>> f = open('/root/test.py','r')
>>> os.path.basename(f.name)
'test.py'
>>> f.name
'/root/test.py'
>>> os.path.getsize(f.name)
52
>>> os.path.isabs(f.name)
True
>>> os.path.isdir(f.name)
False

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Open WeChat, select Settings in Me, select General and then select Storage Space, select Management in Storage Space, select the conversation in which you want to restore files and select the exclamation mark icon. Tutorial Applicable Model: iPhone13 System: iOS15.3 Version: WeChat 8.0.24 Analysis 1 First open WeChat and click the Settings option on the My page. 2 Then find and click General Options on the settings page. 3Then click Storage Space on the general page. 4 Next, click Manage on the storage space page. 5Finally, select the conversation in which you want to recover files and click the exclamation mark icon on the right. Supplement: WeChat files generally expire in a few days. If the file received by WeChat has not been clicked, the WeChat system will clear it after 72 hours. If the WeChat file has been viewed,

In Windows, the Photos app is a convenient way to view and manage photos and videos. Through this application, users can easily access their multimedia files without installing additional software. However, sometimes users may encounter some problems, such as encountering a "This file cannot be opened because the format is not supported" error message when using the Photos app, or file corruption when trying to open photos or videos. This situation can be confusing and inconvenient for users, requiring some investigation and fixes to resolve the issues. Users see the following error when they try to open photos or videos on the Photos app. Sorry, Photos cannot open this file because the format is not currently supported, or the file

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

Detailed explanation of Linux file time viewing techniques In Linux systems, file time information is very important for file management and tracking changes. The Linux system records file change information through three main time attributes, namely access time (atime), modification time (mtime) and change time (ctime). This article details how to view and manage this file time information, and provides specific code examples. 1. Check the file time information by using the ls command with the parameter -l to list the files.
