Programing

Python에서 "열기 사용"을 사용하여 여러 파일을 열려면 어떻게해야합니까?

lottogame 2020. 10. 3. 09:45
반응형

Python에서 "열기 사용"을 사용하여 여러 파일을 열려면 어떻게해야합니까?


나는 한 번에 파일의 몇 가지를 변경하려면 IFF에 내가 그들 모두에 쓸 수 있습니다. 어떻게 든 여러 열린 호출을 with문과 결합 할 수 있는지 궁금합니다 .

try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror

이것이 가능하지 않다면이 문제에 대한 우아한 해결책은 어떤 모습일까요?


Python 2.7 (또는 각각 3.1)부터 다음과 같이 작성할 수 있습니다.

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

이전 버전의 Python에서는 때때로 contextlib.nested()컨텍스트 관리자를 중첩 하는 사용할 수 있습니다 . 그러나 여러 파일을 여는 경우 예상대로 작동하지 않습니다. 자세한 내용은 링크 된 문서를 참조하세요.


드물게 다양한 수의 파일을 동시에 열려면 contextlib.ExitStackPython 버전 3.3부터를 사용할 수 있습니다 .

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Do something with "files"

대부분의 경우 다양한 파일 세트가 있지만 차례로 열어보고 싶을 것입니다.


그냥 교체 and,하면됩니다 :

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

한 번에 많은 파일을 열거 나 긴 파일 경로의 경우 여러 줄로 나누는 것이 유용 할 수 있습니다. 로부터 파이썬 스타일 가이드 다른 답변에 의견 @Sven Marnach에 의해 제안 :

with open('/path/to/InFile.ext', 'r') as file_1, \
     open('/path/to/OutFile.ext', 'w') as file_2:
    file_2.write(file_1.read())

중첩 문은 동일한 작업을 수행하며 내 의견으로는 처리하기가 더 간단합니다.

inFile.txt가 있고 동시에 두 개의 outFile에 쓰려고한다고 가정 해 보겠습니다.

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

편집하다:

나는 반대표의 이유를 이해하지 못합니다. 내 대답을 게시하기 전에 코드를 테스트했으며 원하는대로 작동합니다. 질문에서 묻는 것처럼 모든 outFile에 기록합니다. 중복 쓰기가 없거나 쓰기에 실패했습니다. 그래서 나는 왜 내 대답이 틀렸는 지, 차선책인지 또는 그와 비슷한 것으로 간주되는지 정말 궁금합니다.


Python 3.3부터는 모듈 의 클래스 ExitStack사용하여 임의의 수의 파일contextlib 을 안전하게
열 수 있습니다 .

동적 수의 컨텍스트 인식 개체를 관리 할 수 ​​있습니다. 즉, 처리 할 파일 수를 모르는 경우 특히 유용 합니다 .

실제로 문서에 언급 된 표준 사용 사례는 동적 수의 파일을 관리하는 것입니다.

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

If you are interested in the details, here is a generic example in order to explain how ExitStack operates:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(len(stack._exit_callbacks)) # number of callbacks called on exit
    nums = [stack.enter_context(x) for x in xs]
    print(len(stack._exit_callbacks))

print(len(stack._exit_callbacks))
print(nums)

Output:

0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

Late answer (8 yrs), but for someone looking to join multiple files into one, the following function may be of help:

def multi_open(_list):
    out=""
    for x in _list:
        try:
            with open(x) as f:
                out+=f.read()
        except:
            pass
            # print(f"Cannot open file {x}")
    return(out)

fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
print(multi_open(fl))

2018-10-23 19:18:11.361 PROFILE  [Stop Drivers] [1ms]
2018-10-23 19:18:11.361 PROFILE  [Parental uninit] [0ms]
...
# This file contains VM parameters for Trader Workstation.
# Each parameter should be defined in a separate line and the
...

참고URL : https://stackoverflow.com/questions/4617034/how-can-i-open-multiple-files-using-with-open-in-python

반응형