[英]I am new in python I was trying to perform read/write operations but I got this error ->FileNotFoundError: [Errno 2] No such file or directory error?
I found this solution from stackoverflow but will i have to add this piece of code every time i write a code to perform read/write operations.我从stackoverflow找到了这个解决方案,但是每次我编写代码来执行读/写操作时,我都必须添加这段代码。 Or is there any long term solution available for this?
或者有什么长期的解决方案可以解决这个问题?
import os
path = "E:\Python\learn"
os.chdir(path)
f = open('text.txt')
data = f.read()
print(data)
f.close()
I think you need a way to read same file multiple times in your python code.我认为您需要一种在 python 代码中多次读取同一文件的方法。 Use file.seek() to jump to a specific position in a file.
使用 file.seek() 跳转到文件中的特定 position。 However, think about whether it is really necessary to go through the file again.
不过,想想是否真的有必要再通过文件来go。 An Example for file.seek:
file.seek 的示例:
with open(name, 'r+') as file:
for line in file:
# Do Something with line
file.seek(0)
for line in file:
# Do Something with line, second time
Incase you want to re-iterate the file second time and don't want to open the file again, you can follow this syntax:如果您想第二次重新迭代文件并且不想再次打开文件,您可以遵循以下语法:
with open(name, 'r+') as file:
for line in file:
# Do Something with line
for line in file:
# Do Something with line, second time
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.