[英]Issue with Python Not Writing Lines
所以我正在編寫一個腳本來獲取大型 csv 文件並將它們分成塊。 這些文件每個都有相應格式的行:
01/07/2003,1545,12.47,12.48,12.43,12.44,137423
第一個字段是日期。 右邊的下一個字段是時間值。 這些數據點的粒度很細。 我的目標是用 8 天的數據填充文件,所以我想將 8 天的文件中的所有行寫入一個新文件。
現在,我只看到程序每個“塊”寫一行,而不是所有行。 下面顯示的代碼和屏幕截圖包括顯示塊目錄的制作方式以及文件及其內容。
作為參考,顯示的第 8 天和 1559 意味着它在 mod 運算符變為 true 之前存儲了最后一行。 所以我認為一切都以某種方式被覆蓋,因為只有最后一個值被存儲。
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 文檔中查看更多關於open
函數和模式的信息。 它特別提到了'w'
模式:
請注意,'w+' 會截斷文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.