Python:循环遍历列表,将不同的索引项连接到不同的文本文件

Python: loop through list to concatenate different index items to different text files

我正在尝试使用 glob.glob 循环遍历我的文本文件,同时循环遍历单词列表,以便我可以将不同的单词连接到每个文本文件

4个文本文件及内容

File01.txt | File02.txt | File03.txt | File04.txt
bird       | cat        | dog        | fish

四个单词列表:['ONE','TWO','THREE','FOUR']

这是我的代码:

import glob
import os

for name in glob.glob('file*'):
  print(name)

  num = 4
  lst = ['ONE','TWO','THREE','FOUR']

  cnt = 0
  while num > 0:
    lst_loop = lst[cnt]
    print(lst_loop)
    cnt += 1
    num -= 1

    file = open('header', 'w')
    file.write(lst[0])
    file.close()

#    message = "cat header " + name + " > " lst[cnt] + name
#    command = os.popen(message)
#    print(command.read())
#    print(command.close())

我知道 glob 不是 return 序列表,但就目前而言 return 文本文件的顺序是

file03.txt
file01.txt
file02.txt
file04.txt

考虑到这一点,生成的文件和文件名应如下所示:

TWOFile01.txt | THREEFile02.txt | ONEFile03.txt | FOURFile04.txt
TWO           | THREE           | ONE           | FOUR
bird          | cat             | dog           | fish
files = ["File01.txt", "File02.txt", "File03.txt", "File04.txt"]
words = ["ONE", "TWO", "THREE", "FOUR"]
for i in range(len(files)):
    with open(files[i], "a") as f:
        f.write(words[i])
```
import glob
import os

##list has newline character to allow for correct concatenation    
lst = ['ONE\n','TWO\n','THREE\n','FOUR\n']
cnt = 0

for name in glob.glob('file*'):

  lst_loop = lst[cnt]
  print(lst_loop)
  
  ##as I loop I write the contents to a text file called 'header'
  file = open('header', 'w')
  file.write(lst_loop)
  file.close()

  ##I now strip the new line character from the list for naming
  strip = lst_loop.strip("\n")

  ## and concatanate the contents of the header to the current file    
  message = "cat header " + name + " > " + strip + name
  command = os.popen(message)
  print(command.read())
  print(command.close())

  ##counter to loop through list of words
  cnt += 1

像这样的东西应该可以工作

from glob import iglob

words = ["ONE", "TWO", "THREE", "FOUR"]

for word, f in zip(words, sorted(iglob("file*.txt"))):
    with open(f), open(word + f.capitalize(), "w+") as fp, new:
        new.write("\n".join([word, fp.read()]))

注意:如果 words 和使用 glob 模式找到的文件之间的长度不匹配,zip 将不会抛出错误。它将使用最短的可迭代对象然后中断循环。

sorted(iglob("file*.txt")) 应该会为您找到正确的顺序

open(word + f.capitalize(), "w+") 创建一个新文件,如果存在则覆盖

with 语句用于处理文件关闭,即使您在运行时遇到错误。

import glob
    
fls=glob.glob("*.txt") #match all text files
#shorting the list given by glob in ascending order
fls = sorted(fls) #['File01.txt', 'File02.txt', 'File03.txt', 'File04.txt']

lst = ['ONE','TWO','THREE','FOUR']

c = 0
# counter variable c will help us to loop the list 'lst'
for fl in fls:
    with open(fl, 'r+') as f: #open files and read/write mode
        k = f.read().splitlines() #each line into list
        s = lst[c] + "\n" + k[0] #using counter c and variable k will be a list 
        f.seek(0) #move file pointer to starting of file
        f.truncate() #remove everything from starting
        f.write(s) #write the new string 's'
        c = c + 1 #change the counter value to next index in list 'lst'