Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.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
Python 写入for循环内的文本文件_Python - Fatal编程技术网

Python 写入for循环内的文本文件

Python 写入for循环内的文本文件,python,Python,我正在尝试从for循环输出文本。这是我当前的实现 with open('timelog.txt', 'w') as time_log: for x in range(100): time_log.write(t'/ntest') time_log.close() 我现在什么都没写。文本文件已经创建,但看起来根本没有被修改 有什么我遗漏的吗?不要使用time\u log.close(),因为使用上下文管理器将自动关闭文件 with open("file.txt", "

我正在尝试从for循环输出文本。这是我当前的实现

with open('timelog.txt', 'w') as time_log:
    for x in range(100):

        time_log.write(t'/ntest')

time_log.close()
我现在什么都没写。文本文件已经创建,但看起来根本没有被修改


有什么我遗漏的吗?

不要使用
time\u log.close()
,因为使用
上下文管理器将自动关闭文件

with open("file.txt", "w") as ff:
    for i in range(10):
        ff.write("%d\n" % i)
然后检查文件:

$ cat file.txt
0
1
2
3
4
5
6
7
8
9

该代码引发语法错误。您的意思是在write语句中包含“t”吗?如果我删除了它,代码对我来说就可以了。对不起,伙计们,在尝试在这里发布时添加了t,但是它可以在不调用close函数的情况下工作!谢谢你,真是魅力四射!他一回答我就记下来possible@BGlasbey谢谢:)所以额外的一行
time\u log.close()
清除了文件?@usr2564301不,如果
time\u log.close()
无效,代码有什么问题?