簡體   English   中英

無法打開寫入文件

[英]Can't open a write file

我無法將文件作為寫入文件打開。

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

我不知道該怎么辦。

我假設argvsys.argvsys.argv是腳本名稱本身的列表,所有 arguments 都在命令行上傳遞。 因此,您需要對其進行索引:

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

我認為您應該在程序中添加一些檢查,以檢查是否通過了正確數量的 arguments 以及文件是否確實存在等,但這取決於您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM