什么是打开文件的最pythonic方式?

时间:2022-05-10 22:23:13

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

我正在尝试清理我的代码,我很难确定这两种方法中的哪一种被认为是最具pythonic的方式

import os

dir = os.path.dirname(__file__)
str1 = 'filename.txt'
f = open(os.path.join(dir,str1),'r')

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.

虽然第二个似乎是最干净的,但我发现fullPath的声明有点过多,因为它只会被使用一次。

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 ?

一般来说,避免在另一个调用中调用函数是否更好,即使它添加了一行代码?

2 个解决方案

#1


6  

with open('file path', 'a') as f:
   data = f.read()
   #do something with data

or

要么

f = open(os.path.join(dir,str1),'r')
f.close()

#2


1  

file = open('newfile.txt', 'r') 

for line in file:

      print line

OR

要么

lines = [line for line in open('filename')]

If file is huge, read() is definitively bad idea, as it loads (without size parameter), whole file into memory.

如果文件很大,read()绝对是个坏主意,因为它将整个文件加载到内存中(没有大小参数)。

If your file is huge this will cause latency !

如果您的文件很大,这将导致延迟!

So, i don't recommend read() or readlines()

所以,我不推荐read()或readlines()

#1


6  

with open('file path', 'a') as f:
   data = f.read()
   #do something with data

or

要么

f = open(os.path.join(dir,str1),'r')
f.close()

#2


1  

file = open('newfile.txt', 'r') 

for line in file:

      print line

OR

要么

lines = [line for line in open('filename')]

If file is huge, read() is definitively bad idea, as it loads (without size parameter), whole file into memory.

如果文件很大,read()绝对是个坏主意,因为它将整个文件加载到内存中(没有大小参数)。

If your file is huge this will cause latency !

如果您的文件很大,这将导致延迟!

So, i don't recommend read() or readlines()

所以,我不推荐read()或readlines()