-1

I can't open the file as 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()

It's giving this error:

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

If I execute the code from terminal, It's giving me a syntax error for the last double quote of the first print statement.

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

To solve this I've changed the f-string to format.

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

After I executed the code It gave me another error:

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

I don't know what to do.

egegk
  • 1
  • 3
  • 2
    [`sys.argv`](https://docs.python.org/3/library/sys.html#sys.argv) is a list of the script name itself, and all arguments passed on the command line. You'd probably want to index it appropriately in the first two lines of the script. – Jan Christoph Terasa Apr 08 '21 at 10:39
  • Try print(argv) just to see what you’re actually naming your file. I guess it might be an array rather than a single string? – Pam Apr 08 '21 at 10:40
  • SO is no debugging service. – Jan Christoph Terasa Apr 08 '21 at 11:38

1 Answers1

1

I assume argv is sys.argv, and sys.argv is a list of the script name itself, and all arguments passed on the command line. Thus, you need to index it:

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

I think you should add some checks to your program to check whether the correct amount of arguments have been passed, and the file really exists, etc., but that is up to you.

Jan Christoph Terasa
  • 5,781
  • 24
  • 34