Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3读写.txt文件_Python_Python 3.x_Syntax Error - Fatal编程技术网

Python3读写.txt文件

Python3读写.txt文件,python,python-3.x,syntax-error,Python,Python 3.x,Syntax Error,我对Python有点陌生,但我有足够的能力知道我在做什么。我要做的是为一个.txt文件(以及一个变量)写几行,然后打印其中的5个字符 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.wr

我对Python有点陌生,但我有足够的能力知道我在做什么。我要做的是为一个.txt文件(以及一个变量)写几行,然后打印其中的5个字符

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()
然后,它创建文件时没有问题,但是当我添加

print file.read(5)

对于代码,它给了我file.read的语法错误,我不知道为什么。我已经上网好几个小时了,什么也找不到。要么我在谷歌搜索方面非常糟糕,我是个白痴,要么某个东西坏了,要么两者兼而有之。有什么建议吗/

您正在编写Python 3代码。在Python3中,不是一个特殊的语句。函数调用需要括号:

print(file.read(5))

他可能还需要打开文件。@stephernauch:也许吧,但是
SyntaxError
不会因为打开文件失败而出现。我假设有省略的代码,我不会尝试进行心理调试。python3通常很适合生成“youneedparenstocallprint”错误,但如果行中有其他括号,它会放弃,并给出一个空白的
语法错误:
(如本例)。