【问题标题】:Reading from the first line in a multiline string从多行字符串的第一行读取
【发布时间】:2020-06-16 05:16:58
【问题描述】:

我有一个目录,文件如下:

ab_list
bd_list
cd_list
mno_list
hk_list 
pd_list

我在此目录之外还有另一个名为 testfile 的文件:

abc
que nw

ab_list   ON   8
gs_list   ON   9
hk_list   OFF  9
bd_list   ON   7
cd_list   OFF  6
fr_list   ON   5
mno_list  ON   4
pq_list   OFF   6
jk_list   ON   7
pd_list   OFF  8

我想比较 2 和所有带有文件名和 ON 的文件(如果匹配),它们的内容应该合并到一个名为 merge_file 的新文件中。与 testfile 匹配但为 OFF 的其他文件,其文件名应打印在 new_file 中。 ab_list bd_list 和 mno_list 的内容应该合并到 top_file 中

这是我到目前为止尝试过的代码:

from glob import glob

test_file_directory = "C:\\Users\\User\\Desktop\\Folder\\"

files1 = glob("*.txt")
with open(test_file_directory+"testfile.txt","r") as f:
    files2 = [' '.join([l.split()[0],l.split()[1]]) for l in f.readlines()[3:]]

for f1 in files1:
    for f2 in files2:
        if f1[:-4]+'   ON' == f2:
            #print('match')
            with open('merge_file.txt','a') as a:
                with open(f1,'r') as r:
                    a.write(r.readlines()[1:]+'\n')
        elif f1[:-4]+'   OFF' == f2:
            #print('match')
            with open('match_file.txt','a') as a:
                with open(f1,'r') as r:
                    a.write(f"{f2} {len(r.readlines())}\n")
elif f1[:-4]+'   ON' == f2:
            #print('match')
            with open('match_file.txt','a') as a:
                with open(f1,'r') as r:
                    a.write(f"{f2} {len(r.readlines())}\n")

我希望写入 merge_file 的文件内容开始从文件的第二行而不是第一行读取,并且 match_file 旁边还有带有 ON 的文件名(它从第一个 elif 开始为 OFF) a.write(r.readlines()[1:]+'\n' 这一行给出一个错误,说它是一个字符串而不是一个列表。

【问题讨论】:

  • 您可以创建一个迭代器 - 使用 next() 调用,然后继续使用 for loop 中的其余值。
  • 你能帮我写代码吗
  • 我应该如何在这段代码中使用它
  • 我可能会有点,但我会试一试
  • 你能不能也看看提到的第二个问题

标签: python python-3.x merge compare


【解决方案1】:

a.write(r.readlines()[1:]+'\n')

它使用 r.readlines()[1:] 和 '\n' 执行添加。

r.readlines()[1:] 是文件中每一行的列表。

所以你有错误

TypeError:只能将列表(不是“str”)连接到列表

你应该做的是用'\n'加入列表中的所有行,例如

a.write('\n'.join(r.readlines()[1:])+'\n')

无论如何,要复制文件的内容,你应该使用 f.read(),而不是 f.readlines()

a.write(r.read()+'\n')

要获取第一行,可以使用str.partition('\n'),它将源字符串分成三个分区,分别为[first_string, '\n', next_string],如

a.write(r.read().partition('\n')[2]+'\n')

【讨论】:

  • 你能不能也看看我的第二个问题
  • 最后提到
  • 第二个问题在哪里?!
  • match_file 的文件名旁边也有 ON (它从第一个 elif 开始为 OFF
  • 和 match_file 也应该有带有行数的 merge_file(名称)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多