Python 如何将变量打印为字符串而不是计数?
我正在尝试搜索多个文本文件,查找在以下情况下发生的“板材外观”计数:Python 如何将变量打印为字符串而不是计数?,python,Python,我正在尝试搜索多个文本文件,查找在以下情况下发生的“板材外观”计数: 临时阵列2[0]=“播放”和临时阵列2[2]=“1”: 我试图将其导出为.csv文件,但是,当我打印“板材外观计数”时,它显示为计数,而不是字符串(我认为它需要是字符串才能导出为.csv) 到目前为止,我得到的代码如下 import os input_folder = 'files' # path of folder containing the multiple text files # create a list w
临时阵列2[0]=“播放”和临时阵列2[2]=“1”
:
我试图将其导出为.csv文件,但是,当我打印“板材外观计数”时,它显示为计数,而不是字符串(我认为它需要是字符串才能导出为.csv)
到目前为止,我得到的代码如下
import os
input_folder = 'files' # path of folder containing the multiple text files
# create a list with file names
data_files = [os.path.join(input_folder, file) for file in
os.listdir(input_folder)]
# open csv file for writing
csv = open('myoutput.csv', 'w')
def write_to_csv(line):
print(line)
csv.write(line)
j=0 # initialise as 0
count_of_plate_appearances=0 # initialise as 0
for file in data_files:
with open(file, 'r') as f: # use context manager to open files
for line in f:
lines = f.readlines()
i=0
while i < len(lines):
temp_array = lines[i].rstrip().split(",")
if temp_array[0] == "id":
j=0
count_of_plate_appearances=0
game_id = temp_array[1]
awayteam = lines[i+2].rstrip().split(",")[2]
hometeam = lines[i+3].rstrip().split(",")[2]
date = lines[i+5].rstrip().split(",")[2]
output_for_csv=(game_id,date,hometeam, awayteam)
print(output_for_csv)
#csv.write(','.join(output_for_csv) + '\n') #write to the csv file. This works
for j in range(i+46,i+120,1): #only check for plate appearances this when temp_array[0] == "id"
temp_array2 = lines[j].rstrip().split(",") #create new array to check for plate apperances
if temp_array2[0] == "play" and temp_array2[2] == "1": # plate apperance occurs when these are true
count_of_plate_appearances=count_of_plate_appearances+1
#print(count_of_plate_appearances)
output_for_csv2=(game_id,date,hometeam, awayteam,[count_of_plate_appearances]) #this is what I want to outpu to the CSV
print(output_for_csv2)
#csv.write(','.join(output_for_csv2) + '\n') #the code does not run when this is uncommented
i=i+1
else:
i=i+1
j=0
count_of_plate_appearances=0
#quit()
csv.close()
*注:每个输出有2行。第一个是没有'计数板外观',这打印到pdf的罚款。第二行是我要打印的内容
我认为它应该是这样的,以便获得.csv输出
('ARI201803300', '2018/03/30', 'ARI', 'COL', '35')
('ARI201803310', '2018/03/31', 'ARI', 'COL', '33')
('ARI201804020', '2018/04/02', 'ARI', 'LAN', '32')
('ARI201804030', '2018/04/03', 'ARI', 'LAN', '38')
有没有关于我如何做到这一点的建议 将其更改为
str
,问题是您将其作为列表插入
output_for_csv2=(game_id,date,hometeam, awayteam,str(count_of_plate_appearances))
csv2的输出=(游戏id、日期、主队、awayteam、str(出场次数))。。。注意str(盘子的出现次数)@Rashid'Lee'Ibrahim非常感谢你!简单的解决方法,我对这个很陌生
output_for_csv2=(game_id,date,hometeam, awayteam,str(count_of_plate_appearances))