4 回答

TA贡献1780条经验 获得超4个赞
错误是由于缺少完整的文件路径。因此,您需要确保“A/B/C/D.dat”应该存在于您尝试作为 myfile 打开的文件中。
您可以将以下代码段添加到您的逻辑中以实现它。
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath=subdir+'/'+file

TA贡献1848条经验 获得超2个赞
尽管您的解决方案不是最干净的。你得到的错误来自
with open (file, 'rt') as myfile:
应该替换为
with open (subdir + "/" + file, 'rt') as myfile:

TA贡献1844条经验 获得超8个赞
听起来您正在寻找子目录中所有 .dat 文件的第三行。使用 pathlib.Path,您可以通过几个简单的步骤完成很多工作。
from pathlib import Path
doc = []
line_number_of_each_file = values = 2
for file in Path('C:/A/B').rglob('*.dat'):
doc.append(file.readtext().splitlines()[line_number_of_each_file])
print(doc)

TA贡献2051条经验 获得超10个赞
我有一个类似的问题。我的文件结构是这样的:
project
|__dir1
| |__file_to_read.txt
|
|__dir2
|__file_reader.py
为了真正找到另一个文件,我必须走出一个目录,到我.py文件的父目录。我最初使用此代码:
import os
current_path = os.path.dirname(__file__)
file_to_read = os.path.relpath('project/dir1/file_to_read', current_path)
这对我有用,但后来我换了一个不同的版本。原因不是您需要担心的任何原因,除了显然下一个模块比os.
from pathlib import Path
parent = Path.cwd().parent
file_to_read = Path(f'{parent}/project/dir1/file_to_read.txt').resolve()
也许这会更可取,因为它更强烈推荐给我。我希望这对您的问题有所帮助。
添加回答
举报