linux系统如何创建python文件_关于Linux:python中的open()如果文件不存在,则不会创建该文件...

如果文件存在,那么以读/写方式打开它的最佳方法是什么?如果不存在,那么创建文件并以读/写方式打开它?根据我读到的,file = open('myfile.dat', 'rw')应该这样做,对吗?

它不适用于我(python 2.6.2),我想知道它是否是一个版本问题,或者不应该像那样工作。

底线是,我只需要一个问题的解决方案。我对其他的东西很好奇,但我所需要的是一个很好的方式来做开场白。

更新:封闭目录可由用户和组写入,而不是其他(我在Linux系统上…所以权限775,换句话说),准确的错误是:

IOError: no such file or directory.

正如S.Mark所提到的,这应该是"可行的"。封闭目录是否可写?

"它对我不起作用"?具体来说,这意味着什么?请提供实际错误消息。

Muksie下面的答案是有效的(Baloo也是如此),但是为了完整性,封闭目录是由用户和组写的,而不是其他的(在Linux系统上……所以权限775,换句话说),确切的错误是ioerror:没有这样的文件或目录。谢谢你们的帮助。

@ S.洛特:完成了。很抱歉。

您应该使用open和w+模式:

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

wtruncates现有的文件。文档:'r+''w+'和开放模式,'a+'(注意在文件更新的文件'w+'truncates)。

这样做的把戏。谢谢你。我现在感觉像是一个白痴,我不阅读的规格。不想"RW"是可以接受的,甚至存在。我必须有一个什么人想。

请注意,如果该文件+扩展和不存在的文件,crucially,seeks to the end。如果你的操作系统读取后立即张开的这路,你会得到什么。你需要的是从一开始第一回:f.seek(0)

的详细说明文档,无

特写镜头,然后是没有提及?

"这不是一个解决方案。该问题是当前目录。无论从剧本到lacks权限创建文件,目录,或目录不是简单的存在。然后open('myfile.dat', 'w')是足够的。

如果路径是在指责目录,目录存在:即确保(file = open('dir/myfile.dat', 'w+') ),确保该文件夹存在dir蟒,又名目录创建,不会是你

"这不是一个解决方案。说:"theredpea OP目录确实是存在的,但有775权限("W"),因此他们能不能写它。

在559 upvotes错误答案……

以下方法的优点是,即使在运行过程中引发异常,文件也会在块的末尾正确关闭。它相当于try-finally,但短得多。

1

2

3with 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()方法设置文件的当前位置。

1

2

3

4

5

6

7f.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.

我尝试这个open(filename,带"+"的myfile):把ioerror [ 2 ]在这样一个错误:文件或目录:为什么它不是创建该文件吗?

"我要你filenameChecked值吗?

是的,我做的。这是一个Unicode字符串。我还想用开放式("{ }"(txt文件),.format myfile’+’):

我不使用的路径。我想打开(’+’"’,""It Gets TypeError异常后)::字符串或Unicode需要coercing到缓冲区中的文件,如果发现os.stat线(myfile).st _尺寸=0:

"我接受os.stat()路径/文件名打开文件,不安。国有企业在这里。

你需要为这个工作的恰当定义编码。Q / 728891 3701431 stackoverflow.com / /

良好做法是使用以下内容:

1

2

3

4

5

6

7

8import 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!

')

这是一个坏到测试文件在它的开放,它可以导致竞争条件(一个文件删除后,它是打开的)。有时被用于争用条件的CAN系统中的漏洞的漏洞。"+"模式的最好的方法是:打开"文件新的文件和它的扩展,appends到现有的文件。不要忘了到这地方在try /包。

1

2

3

4

5>>> import os

>>> if os.path.exists("myfile.dat"):

... f = file("myfile.dat","r+")

... else:

... f = file("myfile.dat","w")

R+表示读/写

这是一unpythonic。而不是检查一个文件是否存在,如果它不应该承担的第一个,第一个,然后把它不是的情况。

甚至更糟的,这个代码是发到比赛的状态。因此,在检查过程中,如果该文件存在,一个过程,可能会interrupted和创建这个文件。

你还将需要两个"W"的旗帜将在操作系统的文件读取和写入模式。

将"rw"改为"w+"

或使用"a+"追加(不删除现有内容)

我的回答是:

1

2

3

4

5

6file_path = 'myfile.dat'

try:

fp = open(file_path)

except IOError:

# If not exists, create the file

fp = open(file_path, 'w+')

江户十一〔0〕为我工作,很好。

在py3k中,您的代码引发ValueError:

1

2

3

4

5>>> open('myfile.dat', 'rw')

Traceback (most recent call last):

File"", line 1, in

open('myfile.dat', 'rw')

ValueError: must have exactly one of read/write/append mode

在python-2.6中,它提升了IOError。

您希望如何处理文件?只写还是读写?

"w"、"a"将允许写入,如果文件不存在,将创建该文件。

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

在介绍开放测试可能存在种族条件。这可能不是一个大交易案例,但保持在心的东西。

"如果你需要从文件读取,该文件已经存在,你是在开它。"谢谢你是我的理智的节能。

我想是r+,不是rw。我只是个初学者,这就是我在文档中看到的。

由于python 3.4,您应该使用pathlib来"触摸"文件。这是一个比本文中建议的更优雅的解决方案。

1

2

3

4

5from pathlib import Path

filename = Path('myfile.txt')

filename.touch(exist_ok=True) # will create file, if it exists will do nothing

file = open(filename)

与目录相同:

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

将w+用于写入文件,如果存在则截断,r+用于读取文件,如果不存在则创建文件,但不写入(并返回空值),或将a+用于创建新文件或附加到现有文件。

1

2

3

4

5

6

7

8

9'''

w write mode

r read mode

a append mode

w+ create file if it doesn't exist and open it in write mode

r+ create file if it doesn't exist and open it in read mode

a+ create file if it doesn't exist and open it in append mode

'''

例子:

1

2

3

4file_name = 'my_file.txt'

f = open(file_name, 'w+') # open file in write mode

f.write('python rules')

f.close()

我希望这有帮助。[fyi正在使用python 3.6.2版

如果你想打开它来读写,我假设你不想在打开它时截断它,你想在打开它之后就可以读取它。这就是我使用的解决方案:

1

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

file.seek(0, 0)

用途:

1

2

3

4

5

6

7

8

9

10import os

f_loc = r"C:\Users

ussell\Desktop\ip_addr.txt"

if not os.path.exists(f_loc):

open(f_loc, 'w').close()

with open(f_loc) as f:

#Do stuff

确保打开文件后将其关闭。with上下文管理器将为您执行此操作。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17import 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('

''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

words = line.split()

print(words)

所以你想把数据写到一个文件中,但前提是它不存在?.

使用鲜为人知的x模式来打开()而不是通常的w模式,可以很容易地解决这个问题。例如:

1

2

3

4

5

6

7

8

9

10

11

12>>> with open('somefile', 'wt') as f:

... f.write('Hello

')

...

>>> with open('somefile', 'xt') as f:

... f.write('Hello

')

...

Traceback (most recent call last):

File"", line 1, in

FileExistsError: [Errno 17] File exists: 'somefile'

>>>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值