【问题标题】:Can't open a write file无法打开写入文件
【发布时间】:2021-04-08 10:37:24
【问题描述】:

我无法将文件作为写入文件打开。

script = argv
filename = argv

print(f"We're going to erase {filename}. ")
print("If you don't want that, hit CTRL-C (^C). ")
print("If you do want that, hit RETURN. ")


input("?")

print("Opening the file...")
target = open(filename, 'w')

print("Truncating the file.  Goodbye!")
target.truncate()

print("Now I'm going to ask you for three lines. ")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm going to write these to the file. ")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("And finally, we close it. ")
target.close()

它给出了这个错误:

line 14, in <module>
   target = open(filename, 'w')
TypeError: expected str, bytes or os.PathLike object, not list 

如果我从终端执行代码,它会给我第一个打印语句的最后一个双引号的语法错误。

line 6
    print(f"We're going to erase {filename}. ")
                                             ^
SyntaxError: invalid syntax

为了解决这个问题,我将 f-string 更改为 format。

print("We're going to erase {}. ".format(filename))

在我执行代码后它又给了我一个错误:

File "ex16.py", line 11, in <module>
    input("?")
  File "<string>", line 0
    
    ^
SyntaxError: unexpected EOF while parsing

我不知道该怎么办。

【问题讨论】:

  • sys.argv 是脚本名称本身的列表,以及在命令行上传递的所有参数。您可能希望在脚本的前两行中适当地对其进行索引。
  • 尝试 print(argv) 只是为了查看您实际命名文件的内容。我猜它可能是一个数组而不是单个字符串?
  • SO 没有调试服务。

标签: python target writefile


【解决方案1】:

我假设argvsys.argvsys.argv 是脚本名称本身的列表,所有参数都在命令行上传递。因此,您需要对其进行索引:

script = argv[0]
filename = argv[1]

我认为您应该在程序中添加一些检查,以检查是否传递了正确数量的参数,以及文件是否确实存在等,但这取决于您。

【讨论】:

  • 我已经索引它,但它仍然给我“解析时意外的 EOF”错误
猜你喜欢
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多