0

I'm somewhat new to Python, but I have enough under my belt to know what I'm doing. What I'm trying to do is write a few lines for a .txt file (as well as a variable), and then print 5 of those characters.

import os
username = "Chad_Wigglybutt"
file = open("testfile.txt", "w")
file.write("Hello .txt file, ")
file.write("This is a test, ")
file.write("Can this write variables? ")
file.write("Lets see: ")
file.write(username)
file.close()

It then creates the file without issue, but when I add

print file.read(5)

to the code, it gives me a syntax error for file.read, and I have no clue why. I've been on the internet for a few hours now and I can't find anything. Either I'm extremely bad at google searching and I'm an idiot, or something's broken, or both. Any tips/ideas? :/

marmeladze
  • 6,468
  • 3
  • 24
  • 45

1 Answers1

1

You're writing Python 3 code. In Python 3, print is a function, not a special statement. You need parentheses for function calls:

print(file.read(5))
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 1
    He likely also needs to open the file. – Stephen Rauch May 28 '17 at 23:29
  • 1
    @StephenRauch: Perhaps, but the `SyntaxError` wouldn't come from failing to open the file. I'm assuming there is omitted code, which I'm not going to attempt to psychically debug. – ShadowRanger May 28 '17 at 23:30
  • python3 is usually good about producing a "you needed parens to call print" error, but if there are other parentheses in the line it gives up and gives a blank `SyntaxError:` (such as this case). – anthony sottile May 28 '17 at 23:33