繁体   English   中英

python无法识别新创建的文件

[英]python not recognizing new created files

我有一个python脚本,它将创建一个文本文件,然后将在此新创建的文件上运行命令。

问题是命令行无法识别新创建的文件,并且我收到文件为空的错误消息。

我的代码是这样的:

randomval是一个函数,它将创建随机字符并将其作为字符串返回。

text_file = open("test.txt", "w")
text_file.write(randomval(20,10))


# do something with the `test.txt` file

但我收到一个错误,文件test.txt为空。

反正有解决办法吗?

发生这种情况的原因是,除非刷新或关闭文件,否则操作系统不会将任何数据写入磁盘。 要确保关闭文件,请使用with语句:

with open("test.txt", "w") as f:
    f.write(randomval(20,10))

print('Whoa, at this point the file descriptor is automatically closed!')

不要忘记关闭文件:

br@ymir:~$ python
Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> file=open('foo.bar','w')
>>> file.write('42\n')
>>>  
[2]+  Stopped                 python
br@ymir:~$ cat foo.bar
br@ymir:~$ fg
python

>>> file.close()
>>> 
[2]+  Stopped                 python
br@ymir:~$ cat foo.bar
42
br@ymir:~$

在尝试对新文件( text_file.flush() )进行操作之前,至少应刷新缓冲区。 最好的方法是关闭文件,然后在需要时重新打开它。

执行f.close() ,然后再次将其打开为text_file = open(“ test.txt”,“ r”)

流到文件仍处于打开状态!!!! 只需尝试: text_file.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM