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

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

问题描述

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

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)

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

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

如何使用Python -file处理.txt -file?

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

我想我们需要在.py文件中有一个参数,这样我们可以使用终端中的语法:

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

此问题由帖子提出此处

推荐答案

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

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)

查看 Python正则表达式文档,了解有关使用匹配对象可以做什么的详细信息。请参阅文档的这一部分,了解为什么我们需要搜索

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天全站免登陆