2016-08-01 70 views
0

我目前正在进行一些数据分析工作,并且在数据预处理方面遇到了一些麻烦。使用字典追加多个文本文件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线有哪些测试字典是否包含任何东西,这样做,我已经测试了内容和文件名。

任何想法我错过了将字典附加到文件?

+2

您的缩进是否正确? 'for'循环块应该在append_record()'里面缩进吗? – Parfait

+1

当输入时,'for file'块会缩进一个额外的停止位置,但假设这只是一个复制粘贴格式错误? – beroe

回答

3

有很多问题,但这里引起麻烦的是您打开finalv2.txt两次。一旦与模式w(并且无所作为),并再次在append_record(),这次与模式a

考虑以下几点:

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 
out_file = os.path.join(OutputPath,OutputFilename) 

size = None 

def append_record(fn, record): 
    with open(fn, 'a') as f: 
     json.dump(record, f) 
     #f.write(json.dumps(record)) 

# Loop through each file in input directory 
for fn in os.listdir(InputPath): 
    # Define full filename 
    in_file = os.path.join(InputPath,fn) 
    if os.path.isfile(in_file): 
     print(" Adding: " + fn) 
     with open(in_file, 'r') as file_in: 
      content = file_in.read() 
      d = {'filename':in_file, 'content':content} 
      print("d['filename']: ", d['filename']) 
      append_record(out_file, d) 

如你预期其中一期工程。

这里:

  • 文件中没有明确打开和关闭,它们是由上下文管理器管理(with
  • 有名为dictfile
  • 您在定义finalv2.txt不再变量一个地方,只有一个地方
  • filename没有定义两次,一次作为输出文件,然后再次作为输入文件。相反,有out_filein_file
  • 您通过输出文件名到您append_record功能
  • 你不(尝试)追加JSON两次 - 一次(你可以选择你更喜欢哪一种方法,它们都工作)
+1

非常感谢! – Strelzik