标签归档:file-permissions

如果不存在,Python中的open()不会创建文件

问题:如果不存在,Python中的open()不会创建文件

如果文件以读/写方式打开,或者以不存在的方式创建,然后以读/写方式打开,最好的方法是什么?根据我的阅读,file = open('myfile.dat', 'rw')应该这样做吗?

它对我不起作用(Python 2.6.2),我想知道这是否是版本问题,或者不应该那样工作或做什么。

最重要的是,我只需要解决这个问题。我对其他东西很好奇,但是我所需要的只是做开始部分的好方法。

封闭目录可由用户和组而非其他用户(我在Linux系统上…因此权限775)可写,确切的错误是:

IOError:没有这样的文件或目录。

What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right?

It is not working for me (Python 2.6.2) and I’m wondering if it is a version problem, or not supposed to work like that or what.

The bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.

The enclosing directory was writeable by user and group, not other (I’m on a Linux system… so permissions 775 in other words), and the exact error was:

IOError: no such file or directory.


回答 0

您应该使用open以下w+模式:

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

You should use open with the w+ mode:

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

回答 1

以下方法的优点是,即使在途中引发了异常,文件也会在块的末尾正确关闭。它等效于try-finally,但要短得多。

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

a +打开一个文件以进行附加和读取。如果文件存在,则文件指针位于文件的末尾。该文件以追加模式打开。如果该文件不存在,它将创建一个用于读取和写入的新文件。- Python的文件模式

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”之一-请参阅Stack Overflow问题Python文件模式详细信息

The advantage of the following approach is that the file is properly closed at the block’s end, even if an exception is raised on the way. It’s equivalent to try-finally, but much shorter.

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

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. –Python file modes

seek() method sets the file’s current position.

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

Only “rwab+” characters are allowed; there must be exactly one of “rwa” – see Stack Overflow question Python file modes detail.


回答 2

好的做法是使用以下方法:

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')

Good practice is to use the following:

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')

回答 3

将“ rw”更改为“ w +”

或使用“ a +”进行附加(不删除现有内容)

Change “rw” to “w+”

Or use ‘a+’ for appending (not erasing existing content)


回答 4

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

r +表示读/写

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

r+ means read/write


回答 5

从python 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)

Since python 3.4 you should use pathlib to “touch” files.
It is a much more elegant solution than the proposed ones in this thread.

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)

Same thing with directories:

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

回答 6

我的答案:

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

My answer:

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

回答 7

'''
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()

我希望这有帮助。[仅供参考,请使用python 3.6.2版]

'''
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
'''

example:

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

I hope this helps. [FYI am using python version 3.6.2]


回答 8

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

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises 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

in python-2.6 it raises IOError.


回答 9

采用:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

注意:打开文件后必须将其关闭,with上下文管理器是让Python为您解决此问题的一种好方法。

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.


回答 10

您想对文件做什么?只写它还是读和写?

'w''a'将允许写入,如果文件不存在,则会创建该文件。

如果需要读取文件,则在打开文件之前必须先将其存在。您可以在打开它之前测试它的存在或使用try / except。

What do you want to do with file? Only writing to it or both read and write?

'w', 'a' will allow write and will create the file if it doesn’t exist.

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.


回答 11

我认为r+不是rw。我只是一个入门者,这就是我在文档中看到的内容。

I think it’s r+, not rw. I’m just a starter, and that’s what I’ve seen in the documentation.


回答 12

使用w +写入文件,如果存在则截断,使用r +读取文件,如果文件不存在则创建一个,但不写入(并返回null),或者使用a +创建新文件或追加到现有文件。

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.


回答 13

因此,您想将数据写入文件,但前提是该文件尚不存在?

通过使用鲜为人知的x模式open()而不是通常的w模式,可以轻松解决此问题。例如:

 >>> 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'
  >>>

如果文件是二进制模式,请使用模式xb而不是xt。

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.


回答 14

如果您想打开它进行读写,那么我假设您不想在打开文件时截断它,并且希望在打开文件后立即读取文件。所以这是我正在使用的解决方案:

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

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)

回答 15

也许这会有所帮助

首先将os模块导入py文件

import os

然后创建一个名为save_file的变量并将其设置为您要制作html或txt的文件,在这种情况下,将其设置为txt文件

save_file = "history.txt"

然后定义一个函数,该函数将使用os.path.is file方法检查文件是否存在,如果不存在,它将创建一个文件

def check_into():
if os.path.isfile(save_file):
    print("history file exists..... \nusing for writting....")
else:
    print("history file not exists..... \ncreating it..... ")
    file = open(save_file, 'w')
    time.sleep(2)
    print('file created ')
    file.close()

最后调用函数

check_into()

may be this will help

first import os module into your py file

import os

then create a variable named save_file and set it to file you want to make html or txt in this case a txt file

save_file = "history.txt"

then define a function that will use os.path.is file method to check if file exist and if not it will create a file

def check_into():
if os.path.isfile(save_file):
    print("history file exists..... \nusing for writting....")
else:
    print("history file not exists..... \ncreating it..... ")
    file = open(save_file, 'w')
    time.sleep(2)
    print('file created ')
    file.close()

and at last call the function

check_into()

回答 16

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)
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)