Python 3中的“print file.read()”语法无效

2024-04-18 18:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个10个文件,其中每个文件的第一句话都有一个“blob”单词,然后直接读取这些句子。 这是我的代码:

import random
import string

for i in range(9):
    name = input('fileNumber')+ str(i+1) + '.txt'
    try:
        file = open(name,'w+')
        file = open(name,'a')
        file.write("blob")
        file = open(name,'r')
        print file.read()       #'file' being highlighted with red color when I execute
        file.close()

当我运行它时,我收到一条错误消息说Invalid syntax,它突出显示了我的file.read()行。

有人能告诉我我的代码缺陷在哪里吗?

编辑:我目前正在使用Python3.5。不过,我也可以切换到2.7!


Tags: 文件代码nameinimportforreadstring