01/10/2018, 16:32

Lỗi đọc và ghi file với Python

em đang tập tành học python thông qua những video trên youtube của anh đạt nhưng khi làm tới bài đọc và ghi file thì mắc lỗi, em chạy python trên nền của máy Mac và khi em run đoạn code này :
from sys import argv

script = argv
filename = argv

print("We're going to ease %r" % (filename))
print("If you don't want that, hit CTRL-C (^C)")
print("If you do wan 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("
")
target.write(line2)
target.write("
")
target.write(line3)
target.write("
")

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

thì mắc lỗi này (Opening the file…

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    target = open(filename, "w")
TypeError: expected str, bytes or os.PathLike object, not list) 

và em không biết cách fix như thế nào mong được các cao nhân giúp đỡ

HK boy viết 18:35 ngày 01/10/2018

target = open(filename, “w”)
TypeError: expected str, bytes or os.PathLike object, not list)

Lỗi này chẳng liên quan đến macbook.

Bạn xem lại filename của bạn có phải là string hay không.

script = argv
filename = argv

argv là list, script với filename đều gán vào cái list này thì làm sao filename là string được đây?

Divic Huy viết 18:32 ngày 01/10/2018

Theo như hướng dẫn là vậy, mình chỉ áp dụng vào test thử, cảm ơn bạn nhiều mình đã hiểu rồi

Bài liên quan
0