簡體   English   中英

將路徑名寫入文件 (Python)

[英]Write Path Names to a File (Python)

我正在處理大量圖像,並試圖搜索 jpeg,然后將它們的路徑寫入文件。

目前,我可以找到我想要的所有 jpeg。 但是,我的“索引”文件中的每個新路徑都會覆蓋最后一個。 因此,它根本不是一個索引/列表,而是一個包含 a/path/to/just/one/file.jpg 的文本文件

我已經簡化了我的代碼並將其添加到下面。 這很冗長,但這是為了我的閱讀利益以及像我這樣的新人。

#----------
#-->Import Modules

#I'm pretty sure there is redundancy here and it's not well laid out
#but I'm new to coding and it works

import os
import pathlib

import glob, os
from pathlib import Path

import os.path
from os import path

#----------
#-->Global Vars

#Simplified example of my variables
working_dir = "/Users/myname/path/to/working dir"
records_dir = str(working_dir + "/Records")

#----------
#-->Search Location

#Define where the jpeg search is to take place
#(actually dictated via user input, Minecraft is just an example)
search_locations = ["/Users/myname/minecraft"]

#---------
#--> Search for jpgs and write their paths to a file

#define the file where the jpeg paths are to be stored,
#(I'm referring to the storage file as an index of sorts)
jpg_index = str(records_dir + "/index_for_all_jpgs")


#Its embedded in a forloop because the user can add multiple locations
for search_location in search_locations:
    #get the desired paths from the search location
    for path in Path(search_location).rglob('*.jpg'):
        #Open the index where paths are to be stored
        with open(jpg_index, 'w') as filehandle:
            #This is supposed to write each paths as a new line
            #But it doesn't work
            filehandle.writelines('%s\n' % path)

我也嘗試過使用更簡單的想法;

filehandle.write(path)

還有一個我不完全理解的更復雜的;

filehandle.writelines("%s\n" % path for path in search_location)

然而,我所做的一切都以稍微不同的方式失敗了。

'w' 選項告訴 open() 方法覆蓋 jpg_index 文件中以前的任何內容。 因為每次在編寫 jpeg 路徑之前都會調用此方法,所以只剩下最后一個。 使用 'a'(追加)代替 'w'(寫入)來告訴 open() 方法 append 到文件,而不是每次都覆蓋它。

例如:

for search_location in search_locations:
    for path in Path(search_location).rglob('*.jpg'):
        with open(jpg_index, 'a') as filehandle:
            filehandle.writelines('%s\n' % path)

或者,您可以將 with... as 語句移到 for 循環之外。 這樣,jpg_index 文件只會在開始時打開和覆蓋一次,而不是在其中已有信息之后。

例如:

with open(jpg_index, 'w') as filehandle:
    for search_location in search_locations:
        for path in Path(search_location).rglob('*.jpg'):
            filehandle.writelines('%s\n' % path)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM