在Python中循环文件并应用函数

2024-10-02 06:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些dxf文件,希望将它们转换为geojson文件:

import subprocess
from subprocess import call
import os

working_directory = 'D:/dxf_files/'

for subdir, dirs, files in os.walk(working_directory):
    for file in files:
        if file.endswith('.dxf'):
            print(file)

输出:

BJ-SZZDS-1010084246-dongta-11.dxf
BJ-SZZDS-1010084246-dongta-12.dxf
BJ-SZZDS-1010084246-dongta-17.dxf
BJ-SZZDS-1010084246-dongta-18.dxf
BJ-SZZDS-1010084246-dongta-19.dxf
...

我想把这些文件放在下面的input_file中,通过替换文件的扩展名保持output_file文件名与input_file相同。现在两个代码块是分开的,我怎样才能把它们组合在一起呢?谢谢你的帮助。你知道吗

input_file = 'BJ-SZZDS-1010084246-dongta-11.dxf'
output_file = 'BJ-SZZDS-1010084246-dongta-11.geojson'

def dxf2geojson(output_file, input_file):
    command = ['ogr2ogr', '-f', 'GeoJSON', output_file, input_file]
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return p
dxf2geojson(output_file, input_file)  

Tags: 文件importdxfinputoutputosgeojsonfiles
3条回答

您可以通过将文件迭代代码中的打印函数替换为转换函数来实现这一点。你知道吗

import subprocess
from subprocess import call
import os

working_directory = 'D:/dxf_files/'

for subdir, dirs, files in os.walk(working_directory):
    for file in files:
        if file.endswith('.dxf'):
            input_file = file
            output_file = file[:-3]+'geojson'
            P = dxf2geojson(output_file, input_file)

首先,可以将所有文件名保存在列表中,例如file_list

import subprocess
from subprocess import call
import os

working_directory = 'D:/dxf_files/'

file_list = []   # define file_list to save all dxf files
for subdir, dirs, files in os.walk(working_directory):
    for file in files:
        if file.endswith('.dxf'):
            file_list.append(file)   # save the filenames in file_list

然后,从file_list执行每个文件:

def dxf2geojson(output_file, input_file):
    command = ['ogr2ogr', '-f', 'GeoJSON', output_file, input_file]
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return p

for input_file in file_list:
    f = input_file[:-4]  # to omit .dxf
    output_file = f + '.geojson'    # add file extension .geojson
    dxf2geojson(output_file, input_file)  

您可以将所有文件保存到一个列表中,然后对其进行迭代。你知道吗

import subprocess
from subprocess import call
import os

working_directory = 'D:/dxf_files/'
def_list = []

for subdir, dirs, files in os.walk(working_directory):
  for file in files:
    if file.endswith('.dxf'):
      dxf_list.append(file)


def dxf2geojson(output_file, input_file):
  command = ['ogr2ogr', '-f', 'GeoJSON', output_file, input_file]
  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  return p


for  dex_file in dexf_list:
  output_file = dex_file[:-4] + '.geojson'
  dxf2geojson(output_file, dex_file)

相关问题 更多 >

    热门问题