Python3 File close() 方法、Python3 os.getcwd() 方法

Python3 File close() 方法


概述

close() 方法用于关闭一个已打开的文件。关闭后的文件不能再进行读写操作, 否则会触发 ValueError 错误。 close() 方法允许调用多次。

当 file 对象,被引用到操作另外一个文件时,Python 会自动关闭之前的 file 对象。 使用 close() 方法关闭文件是一个好的习惯。

语法

close() 方法语法如下:

fileObject.close();

参数

返回值

该方法没有返回值。

实例

以下实例演示了 close() 方法的使用:

#!/usr/bin/python3

# 打开文件
fo = open("youj.txt", "wb")
print("文件名为: ", fo.name)

# 关闭文件
fo.close()

以上实例输出结果为:

文件名为:  youj.txt

Python3 os.getcwd() 方法


概述

os.getcwd() 方法用于返回当前工作目录。

语法

getcwd()方法语法格式如下:

os.getcwd()

参数

返回值

返回当前进程的工作目录。

实例

以下实例演示了 getcwd() 方法的使用:

#!/usr/bin/python3

import os, sys

# 切换到 "/var/www/html" 目录
os.chdir("/var/www/html" )

# 打印当前目录
print ("当前工作目录 : %s" % os.getcwd())

# 打开 "/tmp"
fd = os.open( "/tmp", os.O_RDONLY )

# 使用 os.fchdir() 方法修改目录
os.fchdir(fd)

# 打印当前目录
print ("当前工作目录 : %s" % os.getcwd())

# 关闭文件
os.close( fd )

执行以上程序输出结果为:

当前工作目录 : /var/www/html
当前工作目录 : /tmp

猜你喜欢

转载自blog.csdn.net/m0_67373485/article/details/129898603
今日推荐