python - Python 不写行的问题

标签 python file parsing

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

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

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

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

作为引用,显示的第 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

最佳答案

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

您正在以 '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

关于python - Python 不写行的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735262/

相关文章:

json - 如何在没有案例类的情况下解析 JSON Scala

python - 运行时错误 : working outside of request context When request used in first line of method

c++ - 使用 Visual Studio .ncb 文件进行反射

c# - 在标签文本中显示文件名

java - 如何将 boolean 表达式字符串转换为对象?

c# - 在 C# 中将非常长的日期格式解析为 DateTime

python - 如何使用 Selenium 库在 Robot Framework 中编写测试用例

python - 无法在 Windows 中安装 Pillow

Python Spotify OAuth 流程

regex - 使用正则表达式解析文本文件