【问题标题】:how to use list elements as input to file open? [duplicate]如何使用列表元素作为文件打开的输入? [复制]
【发布时间】:2021-11-09 16:38:17
【问题描述】:

对于 SO 管理员/模组。

此问题已标记为已关闭,与此问题重复: How to read a file line-by-line into a list?

真是太棒了。这与这个问题无关,除了它还涉及一个列表。 Didja 懒得看这个问题了吗?

Python 3 和 2.7.8。

我有一个脚本,它根据关键字的存在被解析成块。关键字后面的 argv 是要处理的文件。直到关键字的所有参数都被放入一个列表(inp_to_process)中。所有文件都是简单的 ascii 文件,位于当前文件夹中。

我想打开列表中包含的文件,但我的脚本失败了。我正在做同样的事情来打开关键字后指定的文件,所以我认为我的问题与使用列表元素作为参数有关。

我无法在列表中执行 m,也无法使用范围 - 尝试打开给定文件时都会抛出异常。

这一个有效: 尝试: 使用 open(f_target) 作为 FT: content_target = [line.rstrip('\n') for line in FT] 除了: # 目前似乎也打印了括号..

print ('Error! Unable to open file', f_target)
exit()

这是完成这两种方法的工作(当前已损坏)的代码块:

    for x in range(0, len(inp_to_process)):
    print (inp_to_process[x])
    try:
        with open (inp_to_process[x], "t") as d_input:
            data = d_input.read()
            print (len(data))
    except:
       print ('Error processing input file ' + inp_to_process[x])
exit()

   for m in inp_to_process:
   ifile = m
   try:
        print ('trying: ' + ifile)
        with open (ifile, "t") as d_input:
        print ('after open()')
            data = d_input.read()
            print (len(data))
            # content = [line.rstrip('\n') for line in d_input]
            # if not content in all_inp:
            #    all_inp.add(content)
   except:
       print ('Error processing input file ' + m)

那么我怎样才能访问列表元素,以便它们在打开文件命令中起作用??

谢谢!

【问题讨论】:

    标签: python list loops


    【解决方案1】:

    好的,在一位同事想通后,我有工作代码:

    for num in inp_to_process[:]:
    try:
        with open(num, "r") as f:
            content = [line.rstrip('\n') for line in f]
            print ('data length: ', str(len(content)), num)
    except:
       print ('Error processing input file ' + num)
    

    这将解析列表并根据需要打开指定的文件。 干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      相关资源
      最近更新 更多