我的问题是,我有如下所示的文本文件。我想在这个文件中提取整数部分,但每次提取单个条目,因此每个单个条目将被保存到一个新的txt文件中,该文件的名称为(0000.txt, 0001.txt),根据文件中存在的内容。所有这些文本文件都将保存在video0001,以此类推,直到文本文件完成。
video_0001/00000.png 465,730,533,848,0 1398,654,1486,892,0
video_0001/00001.png 465,730,533,848,0 1398,654,1486,892,0
video_0002/00000.png 465,730,533,848,0 1398,654,1486,892,0
video_0002/00000.png 465,730,533,848,0 1398,654,1486,892,0
video_0003/00001.png 465,730,533,848,0 1398,654,1486,892,0
下面是我的代码:
with open('copy.txt', 'r') as rf:
L = rf.readline()
folder_name, file_name = L.split('/')
filename, integers = file_name.split("d")
print(integers)
#with open('0000.txt', 'w') as wf:
#wf.write()
如有任何帮助,不胜感激
The expected results should be
Video0001 (this is present in the text file and I have a directory named video0001 so I want to save those text file in it)
Have a 0000.txt (This file contains 465,730,533,848,0 1398,654,1486,892,0 ) [should be saved with the same name as in the second column.
Video0001
0000.txt [ 465,730,533,848,0 1398,654,1486,892,0 ]
0001.txt [ 465,730,533,848,0 1398,654,1486,892,0 ]
Video002
0000.txt [465,730,533,848,0 1398,654,1486,892,0]
0002.txt [465,730,533,848,0 1398,654,1486,892,0]
这些文件夹应该与我自己在本地保存的同名文件夹匹配,并按照上面的描述保存。txt文件
如果您想保存在相同的文件夹中,那么您可以获得完整的路径video_0001/00000.png
,并将.png
替换为.txt
,并在open()
中使用此路径video_0001/00000.txt
如果你在不同的文件夹中运行代码,那么你可能需要使用字符串'/absolute/path/to/video_0001/00000.txt'
如果你的文件夹没有_
,那么你可以添加.replace('_', '')
。
如果你的文件夹有上部V
而不是下部v
,那么你可以添加.replace('v', 'V')
像这样:
我使用io
只是为了模拟内存中的文件-所以每个人都可以复制和运行它-但是你应该使用open()
从真实的文件中读取。
text = '''video_0001/00000.png 465,730,533,848,0 1398,654,1486,892,0
video_0001/00001.png 465,730,533,848,0 1398,654,1486,892,0
video_0002/00000.png 465,730,533,848,0 1398,654,1486,892,0
video_0002/00000.png 465,730,533,848,0 1398,654,1486,892,0
video_0003/00001.png 465,730,533,848,0 1398,654,1486,892,0'''
import io
#with open('copy.txt', 'r') as rf:
with io.StringIO(text) as rf:
for line in rf:
old_path, data = line.split(" ", 1)
data = data.strip()
new_path = old_path.replace('.png', '.txt')
new_path = new_path.replace('_', '')
new_path = new_path.replace('v', 'V')
#new_path = '/absolute/path/to/' + new_path
print('old_path:', old_path)
print('new_path:', new_path)
print('data:', data)
print('---')
with open(new_path, 'w') as wf:
wf.write(data)
它显示:
old_path: video_0001/00000.png
new_path: Video0001/00000.txt
data: 465,730,533,848,0 1398,654,1486,892,0
---
old_path: video_0001/00001.png
new_path: Video0001/00001.txt
data: 465,730,533,848,0 1398,654,1486,892,0
---
old_path: video_0002/00000.png
new_path: Video0002/00000.txt
data: 465,730,533,848,0 1398,654,1486,892,0
---
old_path: video_0002/00000.png
new_path: Video0002/00000.txt
data: 465,730,533,848,0 1398,654,1486,892,0
---
old_path: video_0003/00001.png
new_path: Video0003/00001.txt
data: 465,730,533,848,0 1398,654,1486,892,0