我无法将文件作为写入文件打开。
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 字符串更改为格式。
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
我不知道该怎么办。
答案 0 :(得分:1)
我假设 argv
是 sys.argv
,而 sys.argv
是脚本名称本身的列表,以及在命令行上传递的所有参数。因此,您需要对其进行索引:
script = argv[0]
filename = argv[1]
我认为您应该在您的程序中添加一些检查,以检查是否传递了正确数量的参数,以及文件是否确实存在等,但这取决于您。