Skip to main content
 首页 » 编程设计

python之Python 不写行的问题

2025年05月04日17mfrbuaa

所以我正在编写一个脚本来获取大型 csv 文件并将它们分成 block 。这些文件每个都有相应格式的行:

01/07/2003,1545,12.47,12.48,12.43,12.44,137423

第一个字段是日期。右边的下一个字段是时间值。这些数据点的粒度非常小。我的目标是用 8 天的数据填充文件,因此我想将一个文件中 8 天的所有行写入一个新文件。

现在,我只看到程序为每个“ block ”写一行,而不是所有行。下面显示的代码和屏幕截图包括显示 block 目录是如何制作的以及文件及其内容。

作为引用,显示的第 8 天和 1559 意味着它在 mod 运算符变为真之前存储了最后一行。所以我认为一切都以某种方式被覆盖,因为只存储了最后的值。

import os  
import time 
 
 
CWD = os.getcwd() 
WRITEDIR = CWD+"/Divided Data/" 
if not os.path.exists(WRITEDIR): 
    os.makedirs(WRITEDIR) 
 
FILEDIR = CWD+"/SP500" 
os.chdir(FILEDIR) 
 
valid_files = [] 
filelist = open("filelist.txt", 'r') 
 
 
for file in filelist: 
    cur_file = open(file.rstrip()+".csv", 'r') 
    cur_file.readline() #skip first line 
    prev_day = "" 
 
    count = 0 
    chunk_count = 1 
 
    for line in cur_file: 
 
        day = line[3:5] 
 
        WDIR = WRITEDIR + "Chunk" 
        cur_dir = os.getcwd() 
 
 
        path = WDIR + " "+ str(chunk_count) 
        if not os.path.exists(path): 
            os.makedirs(path) 
 
        if(day != prev_day): 
      #      print(day) 
            prev_day = day 
            count += 1 
 
            #Create new directory 
            if(count % 8 == 0): 
                chunk_count += 1 
 
                PATH = WDIR + " " + str(chunk_count) 
                if not os.path.exists(PATH): 
                    os.makedirs(PATH) 
 
 
                print("Chunk count: " + str(chunk_count)) 
                print("Global count: " + str(count)) 
 
 
        temp_path = WDIR +" "+str(chunk_count) 
        os.chdir(temp_path) 
 
        fname = file.rstrip()+str(chunk_count)+".csv" 
        with open(fname, 'w') as f: 
            try: 
                f.write(line + '\n') 
            except:  
                print("Could not write to file. \n") 
 
        os.chdir(cur_dir) 
 
        if(chunk_count >= 406): 
            continue         
 
cur_file.close() 
 
 
 
 
 
 
#    count += 1 

请您参考如下方法:

答案在评论中,但让我在这里给出,以便您的问题得到解答。

您正在以 'w' 模式打开您的文件,这会覆盖所有先前写入的内容。您需要以 'a'(追加)模式打开它:

fname = file.rstrip()+str(chunk_count)+".csv" 
with open(fname, 'a') as f: 

在 Python documentation 中查看有关 open 功能和模式的更多信息.它特别提到了 'w' 模式:

note that 'w+' truncates the file