打开文件的最pythonic方法是什么? [英] What is the most pythonic way to open a file?
本文介绍了打开文件的最pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图稍微清理一下我的代码,但是我很难确定这两种方式中哪一种被认为是最pythonic的方式
I'm trying to clean up my code a little bit, and I have trouble figuring which of these 2 ways is considered the most pythonic one
import os
dir = os.path.dirname(__file__)
str1 = 'filename.txt'
f = open(os.path.join(dir,str1),'r')
尽管第二个似乎是最干净的,但是我发现fullPath的声明有点太多,因为它只会被使用一次.
Although the second seems to be cleanest one, I find the declaration of fullPath a bit too much, since it will only be used once.
import os
dir = os.path.dirname(__file__)
str1 = 'filename.txt'
fullPath = os.path.join(dir,str1)
f = open(fullPath,'r')
总的来说,即使添加了一行代码,还是避免在另一个调用中调用函数会更好吗?
In general, is it a better thing to avoid calling functions inside of another call, even if it adds a line of code ?
推荐答案
with open('file path', 'a') as f:
data = f.read()
#do something with data
或
f = open(os.path.join(dir,str1),'r')
f.close()
这篇关于打开文件的最pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文