#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
这将产生以下结果:
Read String is : Python is
Current file position : 10
Again read String is : Python is
重命名和删除文件:
Python的os模块提供了一些方法,可以帮助执行文件处理操作,如重命名和删除文件。
要使用这个模块,需要先导入它,然后调用相关的功能。
rename() 方法:
rename()方法有两个参数,当前文件名和新文件名。
语法:
os.rename(current_file_name, new_file_name)
例子
以下是例子来重命名文件test1.txt:
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
remove() 方法:
可以使用remove()方法通过提供参数作为文件名称作为要删除的文件。
语法:
os.remove(file_name)
例子
以下为示例删除现有文件test2.txt:
#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")
Python中的目录:
所有的文件都包含不同的目录中,而在Python中处理这些没有问题。os模块有几种方法,可以帮助创建,删除和更改目录。
mkdir() 方法:
可以使用os模块的mkdir()方法在当前目录下创建目录。需要提供参数,这个方法包含的目录要创建的名称。
语法:
os.mkdir("newdir")
例子:
以下为示例在当前目录下创建test目录如下所示:
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("test")
chdir() 方法:
可以使用chdir()方法来改变当前目录。chdir()方法接受一个参数,那就是要成为当前目录的目录的名称。
语法:
os.chdir("newdir")
例子:
下面是一个进入“/home/newdir”目录的例子:
#!/usr/bin/python
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
getcwd() 方法:
getcwd()方法显示当前的工作目录。
例子:
php中文网:公益在线php培训,帮助PHP学习者快速成长!
Copyright 2014-2020 https://www.php.cn/ All Rights Reserved | 苏ICP备2020058653号-1