php I O操作,详细讲解Python中的文件I/O操作

#!/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号-1e6cebb680dfe320dad7e62bd6442c3a6.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值