Python 用file 对象和open方法处理文件的区别

本文探讨了Python中使用file对象和open方法进行文件操作时遇到的跨平台问题,在Windows下正常运行的代码在Linux环境下出现错误。文章建议始终采用open方法以确保代码的兼容性和稳定性。
摘要由CSDN通过智能技术生成

最近用python处理文件时碰到一个错误,让我仔细对这种用法有了一些深入的研究:

python document 是这么说的:

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.

并且对File 对象的构造函数说明如下:

file(filename[, mode[, bufsize]])

Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

New in version 2.2.

但是其实我在如下代码段中, def setNodeManagerDomain(domainDir):
   try:   
    domainName = os.path.basename(domainDir)
    fd = open(domainDir + '/nodemanager/nodemanager.domains', 'w')
    fd.write('#Domains and directories created by Configuration Wizard.\n')
    fd.write('#' + time.ctime() + '\n')
    dirNorm=os.path.normpath(domainDir).replace('\\','\\\\')
    fd.write(domainName + '=' + dirNorm)
    print 'create domain file and close in the end under the directory:' + domainDir
    fd.close
   except Exception, e:
    print 'Failed to create domain file in the directory:' + domainDir
我使用file对象 or open方法在windows 环境下都能通过,但是程序部署到Linux环境中就出现问题。

    [echo] NameError: file

可能linux环境对file支持不好,所以保险起见,还是遵循文档中所说的,坚持用open方法吧。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值