Python不写行的问题

2024-05-01 21:49:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

2001年7月1日31545,12.47,12.48,12.43,12.44137423

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

现在,我只看到程序每个“块”写一行,而不是所有的行。下面显示的代码和屏幕截图显示了区块目录是如何生成的,以及文件及其内容。你知道吗

作为参考,显示的第8天和1559意味着它存储了mod操作符变为真之前的最后一行。所以我认为一切都被覆盖了,因为只有最后的值被存储了。你知道吗

Example of file and contents after program completion.

Directory structure w/ chunks

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

Tags: 文件pathifoscountlinenotfile
1条回答
网友
1楼 · 发布于 2024-05-01 21:49:15

答案在评论中,但让我在这里给出答案,以便回答您的问题。你知道吗

您正在以'w'模式打开文件,该模式将覆盖以前写入的所有内容。您需要以'a'(append)模式打开它:

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

有关Python documentation中的open函数和模式的更多信息。它特别提到'w'模式:

note that 'w+' truncates the file

相关问题 更多 >