我想要統計所有.txt文件中的所有As和Bs和Cs,並提供一個.csv文件來列出所有這些字母中的一個。通過所有輸入文件循環任務python
這裏的代碼做了我想要的,但只有最後一個文件我提供,而不是所有的人。
我在做什麼錯?
import glob
import csv
#This will print out all files loaded in the same directory and print them out
for filename in glob.glob('*.txt*'):
print(filename)
#A B and C
substringA = "A"
Head1 = (open(filename, 'r').read().count(substringA))
substringB = "B"
Head2 = (open(filename, 'r').read().count(substringB))
substringC = "C"
Head3 = (open(filename, 'r').read().count(substringC))
header = ("File", "A Counts" ,"B Counts" ,"C Counts")
analyzed = (filename, Head1, Head2, Head3)
#This will write a file named Analyzed.csv
with open('Analyzed.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header)
writer.writerow(analyzed)
是在for循環或外面計算'A'' B'和'C'的代碼? –
只是將你的計數代碼4個空格移動到右邊,以便在'for'循環中:) – 9dogs
我認爲這正是我的問題。我不知道如何循環遍歷所有文件的代碼。 – Scarlett