我目前正在进行一些数据分析工作,并且在数据预处理方面遇到了一些麻烦。使用字典追加多个文本文件Python
我编译了一个文本文件的文件夹,文本文件的名称是该文本文件对应的日期。我原本能够将所有的文本文件附加到一个文档中,但我想使用一个字典来获得2个属性,文件名(也是日期)和文本文件中的内容。
这是代码:
import json
import os
import math
# Define output filename
OutputFilename = 'finalv2.txt'
# Define path to input and output files
InputPath = 'C:/Users/Mike/Desktop/MonthlyOil/TextFiles'
OutputPath = 'C:/Users/Mike/Desktop/MonthlyOil/'
# Convert forward/backward slashes
InputPath = os.path.normpath(InputPath)
OutputPath = os.path.normpath(OutputPath)
# Define output file and open for writing
filename = os.path.join(OutputPath,OutputFilename)
file_out = open(filename, 'w')
print ("Output file opened")
size = math.inf
def append_record(record):
with open('finalv2.txt', 'a') as f:
json.dump(record, f)
f.write(json.dumps(record))
# Loop through each file in input directory
for file in os.listdir(InputPath):
# Define full filename
filename = os.path.join(InputPath,file)
if os.path.isfile(filename):
print (" Adding :" + file)
file_in = open(filename, 'r')
content = file_in.read()
dict = {'filename':filename,'content':content}
print ("dict['filename']: ", dict['filename'])
append_record(dict)
file_in.close()
# Close output file
file_out.close()
print ("Output file closed")
我遇到的问题是,它不会追加我的文件,我havea线有哪些测试字典是否包含任何东西,这样做,我已经测试了内容和文件名。
任何想法我错过了将字典附加到文件?
您的缩进是否正确? 'for'循环块应该在append_record()'里面缩进吗? – Parfait
当输入时,'for file'块会缩进一个额外的停止位置,但假设这只是一个复制粘贴格式错误? – beroe