python 建立文件夹 出错_使用python创建新文本文件时出错?

使用python创建新文本文件时出错?

此功能不起作用并引发错误。 我需要更改任何参数或参数吗?

import sys

def write():

print('Creating new text file')

name = input('Enter name of text file: ')+'.txt' # Name of text file coerced with +.txt

try:

file = open(name,'r+') # Trying to create a new file or open one

file.close()

except:

print('Something went wrong! Can\'t tell what?')

sys.exit(0) # quit Python

write()

7个解决方案

114 votes

如果该文件不存在,则open(name, 'a')将失败。

您可以使用open(name, 'a'),如果该文件不存在,则会创建该文件,但会截断现有文件。

或者,您可以使用open(name, 'a'); 如果文件不存在,这将创建文件,但不会截断现有文件。

falsetru answered 2019-06-14T20:57:58Z

6 votes

以下脚本将用于创建任何类型的文件,用户输入作为扩展名

import sys

def create():

print("creating new file")

name=raw_input ("enter the name of file:")

extension=raw_input ("enter extension of file:")

try:

name=name+"."+extension

file=open(name,'a')

file.close()

except:

print("error occured")

sys.exit(0)

create()

prathima answered 2019-06-14T20:58:22Z

5 votes

而不是使用try-except块,你可以使用,如果是的话

如果文件不存在,这将不会执行,    开放的(名字,'R +')

if os.path.exists('location\filename.txt'):

print "File exists"

else:

open("location\filename.txt", 'w')

如果文件不存在,'w'会创建一个文件

SriSree answered 2019-06-14T20:58:59Z

3 votes

这很好,但不是

name = input('Enter name of text file: ')+'.txt'

你应该使用

name = raw_input('Enter name of text file: ')+'.txt'

随着

open(name,'a') or open(name,'w')

Ivan answered 2019-06-14T20:59:32Z

1 votes

import sys

def write():

print('Creating new text file')

name = raw_input('Enter name of text file: ')+'.txt' # Name of text file coerced with +.txt

try:

file = open(name,'a') # Trying to create a new file or open one

file.close()

except:

print('Something went wrong! Can\'t tell what?')

sys.exit(0) # quit Python

write()

这将有效:)

asdfme123 answered 2019-06-14T20:59:55Z

1 votes

为简单起见,您可以使用os.system函数:

import os

os.system("touch filename.extension")

这将调用系统终端来完成任务。

answered 2019-06-14T21:00:26Z

0 votes

您可以使用".txt"

但是,当您输入文件名时,请在两侧使用引号,否则无法将".txt"添加到文件名

user3725107 answered 2019-06-14T21:00:57Z

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值