用 Python 导入文本文件

3

我对Python非常陌生。我只是想知道在以下Python脚本中,我们要运行的脚本应该在哪里导入或引用。我只想在下面的脚本中导入或引用一个文件。

```python import os
# Import the file here ``` ```python # 在这里导入文件 ```
请注意,您可以使用相对路径或绝对路径来导入文件。如果文件与脚本位于同一目录中,则可以使用相对路径。否则,请使用绝对路径。
import fileinput, optparse

usage = """%prog HOCOMOCOv9_AD_TRANSFAC.txt > converted_transfac_matrices.txt

 This program reads matrices in a format used by the TRANSFAC database,
 and writes them in a format that can be used by Clover.  The TRANSFAC
 format looks something like this:

 AC  M00002
 XX
 P0      A      C      G      T
 01      4      4      3      0      V
 02      2      5      4      0      S
 03      3      2      4      2      N"""


op = optparse.OptionParser(usage=usage)
(opts, args) = op.parse_args()
if not args: op.error("please specify an input file")

title = []

for line in fileinput.input(args):
    w = line.split()
    key = w[0]
    if key in ("AC", "ID", "NA"):
        title.extend(w[1:])
    elif key.isdigit():
        if title:
            print ">" + " ".join(title)
            title = []
        print "\t".join(w[1:5])

我有点困惑 - 你到底想做什么? - Wayne Werner
我就是找不到在上面的脚本中导入文本文件的方法。我想在文本文件上运行此脚本。我不知道如何引用或导入该特定文本文件。这是我第一次使用Python。 - user2498657
是的,我想在上述脚本中传递文本文件或读取它。是的。 - user2498657
只需使用文件作为参数调用您的脚本:python YOUR_SCRIPT.py YOUR_INPUT_FILE - tobias_k
你好,以下是翻译内容:在上面没有脚本。您在取消删除后的最后一次编辑中将其删除了。 - Bleeding Fingers
显示剩余4条评论
1个回答

5
这个?
with open('file.txt','r') as f_open:
    data = f_open.read()

print data

或者

f_open = open('file.txt','r')
data = f_open.read()
f_open.close()

print data

或者

python script.py

或者

python script.py text.txt

或者

import csv
with open('file.csv', 'rb') as open_csv:
    csv_reader = csv.reader(open_csv)

print csv_reader

有人发布了一篇不太清晰的帖子:S


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接