program tip

Python의 open ()은 파일이 없으면 생성하지 않습니다.

radiobox 2020. 10. 3. 10:24
반응형

Python의 open ()은 파일이 없으면 생성하지 않습니다.


파일이있는 경우 읽기 / 쓰기로 파일을 열거 나없는 경우 파일을 만들고 읽기 / 쓰기로 여는 가장 좋은 방법은 무엇입니까? 내가 읽은 것에서 이것을 file = open('myfile.dat', 'rw')해야합니까?

그것은 나를 위해 작동하지 않으며 (Python 2.6.2) 버전 문제인지 또는 그렇게 작동하지 않아야하는지 궁금합니다.

결론은 문제에 대한 해결책이 필요하다는 것입니다. 나는 다른 것들에 대해 호기심이 많지만 내가 필요한 것은 오프닝 부분을하는 좋은 방법입니다.

업데이트 : 둘러싼 디렉토리는 다른 사람이 아닌 사용자와 그룹이 쓸 수 있었고 (저는 Linux 시스템에 있습니다 ... 즉, 권한 775) 정확한 오류는 다음과 같습니다.

IOError : 해당 파일 또는 디렉토리가 없습니다.


open다음 w+모드 와 함께 사용해야 합니다.

file = open('myfile.dat', 'w+')

다음 접근 방식의 장점은 도중에 예외가 발생하더라도 블록 끝에서 파일이 제대로 닫혀 있다는 것입니다. 와 동일 try-finally하지만 훨씬 더 짧습니다.

with open("file.dat","a+") as f:
    f.write(...)
    ...

a + 추가 및 읽기를 위해 파일을 엽니 다. 파일이있는 경우 파일 포인터는 파일의 끝에 있습니다. 파일이 추가 모드로 열립니다. 파일이 존재하지 않으면 읽기 및 쓰기를위한 새 파일을 생성합니다. - 파이썬 파일 모드

seek () 메서드 는 파일의 현재 위치를 설정합니다.

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

"rwab +"문자 만 허용됩니다. 정확히 "rwa"중 하나가 있어야합니다. 스택 오버플로 질문 Python 파일 모드 세부 정보를 참조하십시오 .


다음을 사용하는 것이 좋습니다.

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
    f.write('Hello, world!\n')

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r +는 읽기 / 쓰기를 의미합니다.


"rw"를 "w +"로 변경

또는 추가를 위해 'a +'를 사용하십시오 (기존 콘텐츠를 지우지 않음).


내 대답 :

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

파이썬 3.4부터 당신이 해야 사용 pathlib"터치"파일.
이 스레드에서 제안한 것보다 훨씬 더 우아한 솔루션입니다.

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

디렉토리도 마찬가지입니다.

filename.mkdir(parents=True, exist_ok=True)

open('myfile.dat', 'a') 나를 위해 작동합니다.

py3k에서 코드가 발생합니다 ValueError.

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

python-2.6에서는 IOError.


'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

예:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

이게 도움이 되길 바란다. [참고로 파이썬 버전 3.6.2를 사용하고 있습니다.]


rw가 아니라 r + 라고 생각합니다 . 나는 단지 시작일 뿐이며 문서에서 본 것입니다.


파일로 무엇을 하시겠습니까? 쓰기 만할까요 아니면 읽기와 쓰기 모두할까요?

'w', 'a'는 쓰기를 허용하고 파일이 없으면 생성합니다.

If you need to read from a file, the file has to be exist before open it. You can test its existence before opening it or use a try/except.


Put w+ for writing the file, truncating if it exist, r+ to read the file, creating one if it don't exist but not writing (and returning null) or a+ for creating a new file or appending to a existing one.


Use:

import os

f_loc = r"C:\Users\Russell\Desktop\ip_addr.txt"

if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

with open(f_loc) as f:
    #Do stuff

Make sure you close the files after you open them. The with context manager will do this for you.


If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I'm using:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

So You want to write data to a file, but only if it doesn’t already exist?.

This problem is easily solved by using the little-known x mode to open() instead of the usual w mode. For example:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

If the file is binary mode, use mode xb instead of xt.


import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

참고URL : https://stackoverflow.com/questions/2967194/open-in-python-does-not-create-a-file-if-it-doesnt-exist

반응형