เหตุใดจึงพยายามพิมพ์ไปยังไฟล์โดยตรงแทนที่จะsys.stdout
ทำให้เกิดข้อผิดพลาดทางไวยากรณ์ต่อไปนี้:
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
File "<stdin>", line 1
print('This is a test', file=f1)
^
SyntaxError: invalid syntax
จากความช่วยเหลือ (__ builtins__) ฉันมีข้อมูลต่อไปนี้:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
แล้วไวยากรณ์ที่ถูกต้องในการเปลี่ยนการพิมพ์สตรีมมาตรฐานคืออะไร?
ฉันรู้ว่าอาจมีวิธีอื่นที่ดีกว่าในการเขียนลงไฟล์ แต่ฉันไม่เข้าใจว่าทำไมถึงเป็นข้อผิดพลาดทางไวยากรณ์
คำอธิบายที่ดีจะได้รับการชื่นชม!
print()
เป็นฟังก์ชันในตัว python 3.x ในขณะที่print
เป็นตัวดำเนินการ python <3.x2.7.2+
โพสต์แสดงให้เห็นว่า