如何将文件名作为参数传递到我的模块中? [英] How can I pass a filename as a parameter into my module?

查看:28
本文介绍了如何将文件名作为参数传递到我的模块中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .py 文件中有以下代码:

导入重新正则表达式 = 重新编译(r"""ULLAT: (?P-?[d.]+).*?ULLON: (?P-?[d.]+).*?LRLAT: (?P-?[d.]+)""", re.DOTALL|re.VERBOSE)

我将 .txt 文件中的数据作为序列:

QUADNAME:rockport_colony_SD分辨率:10 ULLAT:43.625 ULLON:-97.87527466 LRLAT: 43.5 LRLON: -97.75027466 HDATUM: 27 ZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA1200000: QSIGMA12000

如何使用 Python 文件处理 .txt 文件?

我想我们在 .py 文件中需要一个参数,以便我们可以使用类似于终端中的语法:

$ py-file 待处理文件

这个问题是由 此处.

解决方案

您需要读入文件,然后使用正则表达式搜索内容.sys 模块包含一个列表 argv,其中包含所有命令行参数.我们拉出第二个(第一个是用于运行脚本的文件名),打开文件,然后读入内容.

<前>进口重新导入系统文件名 = sys.argv[1]fp = 打开(文件名)内容 = fp.read()正则表达式 = 重新编译(r"""ULLAT: (?P-?[d.]+).*?ULLON: (?P-?[d.]+).*?LRLAT: (?P-?[d.]+)""", re.DOTALL|re.VERBOSE)匹配 = regex.search(内容)

请参阅 Python 正则表达式文档,了解您可以使用的详细信息匹配对象.请参阅文档的这一部分,了解为什么我们需要搜索而不是扫描文件时匹配.

此代码将允许您使用您在问题中指定的语法.

I have the following code in .py file:

import re

regex = re.compile(
    r"""ULLAT: (?P<ullat>-?[d.]+).*?
    ULLON: (?P<ullon>-?[d.]+).*?
    LRLAT: (?P<lrlat>-?[d.]+)""", re.DOTALL|re.VERBOSE)

I have the data in .txt file as a sequence:

QUADNAME: rockport_colony_SD
RESOLUTION: 10 ULLAT: 43.625 ULLON:
-97.87527466 LRLAT: 43.5 LRLON: -97.75027466 HDATUM: 27 ZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5 QUADDATE: 20001001

How can I use the Python -file to process the .txt -file?

I guess that we need a parameter in the .py file, so that we can use a syntax like in terminal:

$ py-file file-to-be-processed

This question was raised by the post here.

解决方案

You need to read the file in and then search the contents using the regular expression. The sys module contains a list, argv, which contains all the command line parameters. We pull out the second one (the first is the file name used to run the script), open the file, and then read in the contents.

import re
import sys

file_name = sys.argv[1]
fp = open(file_name)
contents = fp.read()

regex = re.compile(
    r"""ULLAT: (?P-?[d.]+).*?
    ULLON: (?P-?[d.]+).*?
    LRLAT: (?P-?[d.]+)""", re.DOTALL|re.VERBOSE)

match = regex.search(contents)

See the Python regular expression documentation for details on what you can do with the match object. See this part of the documentation for why we need search rather than match when scanning the file.

This code will allow you to use the syntax you specified in your question.

这篇关于如何将文件名作为参数传递到我的模块中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆