2012-05-21 1 views
1

파이썬 방법에 대한 인수로 파일이나 경로를 사용하는 방법나는 경로 중 열린 파일</p> <pre><code>myFile = open("myFile.txt") obj.writeTo(myFile) myFile.close() </code></pre> <p>또는 문자열을 수락하는 방법을 쓰기 위해 노력하고 있어요

obj.writeTo("myFile.txt") 

메서드는 다음과 같이 구현됩니다

def writeTo(self, hessianFile): 
    if isinstance(hessianFile,file): 
     print("File type") 
    elif isinstance(hessianFile,str): 
     print("String type") 
    else: 
     pass 

을하지만이 오류가 발생합니다

NameError: global name 'file' is not defined 

파일 유형이 정의되지 않은 이유는 무엇입니까? 항상 정의해서는 안되나요? 파일을 유효한 인수 유형으로 올바르게 경로 지정하기 위해 구현을 어떻게 수정해야합니까?

답변

3

입력하지 마십시오! Pythonic이 아닙니다. 당신은 당신이 더 가능성이 생각한다면,

def writeTo(self, hessianFile): 
    try: 
     with open(hessianFile, "w") as f: 
      do_stuff(f) 
    except TypeError: 
     do_stuff(hessianFile) 

또는 : 당신이 예외가 발생하면 더 나은 옵션은 단순히 일반적인 결과를 선택하면 그와 마찬가지로 작업하려고, 다른 방법에 실패하는 것입니다 - 더 읽기, 그리고 또한 항상

def writeTo(self, hessianFile): 
    try: 
     do_stuff(f) 
    except AttributeError: 
     with open(hessianFile, "w") as f: 
      do_stuff(f) 

은 파일 열기를 처리하는 가장 좋은 방법은 the with statement 내 사용을 참고 : 대부분의 시간을 파일 객체를 가져, 그것을 다른 방법으로 주위를 할 당신을 위해, 심지어 예외에 대한 파일.

원래 코드가 실패한 이유는 file이 3.x에서 open()에 의해 반환 된 개체의 기본 클래스가 아니기 때문입니다.

open() 함수가 반환하는 파일 객체 유형은 모드에 따라 다릅니다. open()을 사용하여 텍스트 모드 ('w', 'r', 'wt', 'rt'등)로 파일을 열면 io.TextIOBase 의 하위 클래스를 반환합니다. 특히 io.TextIOWrapper). 버퍼링을 사용하는 바이너리 모드로 파일을 여는 데 사용되는 경우 반환되는 클래스는 io.BufferedIOBase의 하위 클래스입니다. 정확한 클래스는 다양합니다. 읽기 바이너리 모드에서는 이 io.BufferedReader를 반환합니다. 쓰기 바이너리에서 이진 모드를 추가하면 은 io.BufferedWriter를 반환하고 읽기/쓰기 모드에서는 io.BufferedRandom을 반환합니다. 버퍼링을 사용하지 않으면 원시 스트림 인 io.RawIOBase, io.FileIO의 하위 클래스가 반환됩니다. Source

그래서 원하는 경우 io.FileIO.

2

파일과 유사한 객체의 이름으로 'file'(파이썬의 내장 객체)이라는 이름을 사용하지 마십시오.

f = open("myFile.txt") 
obj.writeTo(f) 
f.close() 

예 : 확인

>>> filetype = lambda x: isinstance(x, file) 
>>> file = open('t','w') 
>>> filetype(file) 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 1, in <lambda> 
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types 

>>> f = open('t','w') 
>>> del file 
>>> filetype(f) 
True 
+0

... 파이썬 3에있는 동안. 나는 당신의 오류가 arg2가 제 2 인수가 정의되지 않았다는 내 오류가있는 잘못된 유형이라고 말합니다. ** 이것은 python3 **입니다. –

1

파이썬 3에 이 내장되어 있지만, 파이썬 3에서는 사라졌습니다.다음 비교 : 나는 당신이 제시 한 변화를 만들었지 만, 내 문제가 해결되지 않은

Python 2.7.1 [...] 
>>> f = open('zz.bak', 'w') 
>>> type(f) 
<type 'file'> 
>>> print f.__doc__ 
file(name[, mode[, buffering]]) -> file object 

Open a file. The mode can be 'r', 'w' or 'a' for reading (default), 
writing or appending. The file will be created if it doesn't exist 
when opened for writing or appending; it will be truncated when 
opened for writing. Add a 'b' to the mode for binary files. 
Add a '+' to the mode to allow simultaneous reading and writing. 
If the buffering argument is given, 0 means unbuffered, 1 means line 
buffered, and larger numbers specify the buffer size. The preferred way 
to open a file is with the builtin open() function. 
Add a 'U' to mode to open the file for input with universal newline 
support. Any line ending in the input file will be seen as a '\n' 
in Python. Also, a file so opened gains the attribute 'newlines'; 
the value for this attribute is one of None (no newline read yet), 
'\r', '\n', '\r\n' or a tuple containing all the newline types seen. 

'U' cannot be combined with 'w' or '+' mode. 

Python 3.2.1 [...] 
>>> f = open('xx', 'w') 
>>> type(f) 
<class '_io.TextIOWrapper'> 
>>> print(f.__doc__) 
Character and line based layer over a BufferedIOBase object, buffer. 

encoding gives the name of the encoding that the stream will be 
decoded or encoded with. It defaults to locale.getpreferredencoding. 

errors determines the strictness of encoding and decoding (see the 
codecs.register) and defaults to "strict". 

newline can be None, '', '\n', '\r', or '\r\n'. It controls the 
handling of line endings. If it is None, universal newlines is 
enabled. With this enabled, on input, the lines endings '\n', '\r', 
or '\r\n' are translated to '\n' before being returned to the 
caller. Conversely, on output, '\n' is translated to the system 
default line seperator, os.linesep. If newline is any other of its 
legal values, that newline becomes the newline when the file is read 
and it is returned untranslated. On output, '\n' is converted to the 
newline. 

If line_buffering is True, a call to flush is implied when a call to 
write contains a newline character.