Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python消耗了我所有的RAM和系统挂起_Python_Ram_Gdal - Fatal编程技术网

Python消耗了我所有的RAM和系统挂起

Python消耗了我所有的RAM和系统挂起,python,ram,gdal,Python,Ram,Gdal,我正在尝试使用python从文件夹中的多个tiff文件中提取值。 我使用globglob迭代文件,并根据纬度和经度值提取每个位置的值。我已经编写了代码,开始时运行良好,但最终一直消耗我的ram,系统挂起。我有近5000个这样的文件和200多个位置。代码如下所示 import math,os,sys,glob import gdal from openpyxl import load_workbook f1=('C:\Users\APPLIED\Desktop\SPIE Analysis\Data

我正在尝试使用python从文件夹中的多个tiff文件中提取值。 我使用globglob迭代文件,并根据纬度和经度值提取每个位置的值。我已经编写了代码,开始时运行良好,但最终一直消耗我的ram,系统挂起。我有近5000个这样的文件和200多个位置。代码如下所示

import math,os,sys,glob
import gdal
from openpyxl import load_workbook
f1=('C:\Users\APPLIED\Desktop\SPIE Analysis\Data\Data1.xlsx')
wt = load_workbook(f1, read_only=False)#, keep_vba=True)
sheet1 = wt['Sheet1']
#---------------------------------------------------------------------------
lat = []
file_in = open("C:\Users\APPLIED\Desktop\SPIE Analysis\Data\lat.txt", "r")
for y in file_in.read().split("\n"):
    lat.append(y)
file_in.close
lon = []
file_in = open("C:\Users\APPLIED\Desktop\SPIE Analysis\Data\lon.txt", "r")
for y in file_in.read().split("\n"):
    lon.append(y)
file_in.close
#---------------------------------------------------------------------------
lp=0
y1=2002
print y1
os.chdir("F:\\wget\\Renamed")
for file in glob.glob("*.tif"):
    b=[]
    b=list(file)
    c = file
    a = [b[0],b[1],b[2],b[3]]
    d = [b[4],b[5],b[6]]
    year = int(''.join(a))
    day = int(''.join(d))
    dif=year-2002
    if year!=y1:
        print ""
        print year
        if (year-1)%4==0:
            lp=lp+1
        y1=year
    else:
        sys.stdout.write(">")
    r=day+dif*365+lp+3
    for i in range(0,274):
        u0 = float(os.popen('gdallocationinfo -valonly -wgs84 %s %s %s' % (c, (lon[i]), lat[i])).read())
        if u0<0:
            if u0==-9999:
                sheet1.cell(row=r,column=i+2).value = u0
            else:
                sheet1.cell(row=r,column=i+2).value = 0
        else:
            sheet1.cell(row=r,column=i+2).value = u0/1000
    wt.save(f1)
导入数学、操作系统、系统、全局
导入gdal
从openpyxl导入加载工作簿
f1=('C:\Users\applicated\Desktop\SPIE Analysis\Data\Data1.xlsx')
wt=加载\工作簿(f1,只读=假)\,保持\ vba=真)
sheet1=wt['sheet1']
#---------------------------------------------------------------------------
lat=[]
文件_in=open(“C:\Users\applicated\Desktop\SPIE Analysis\Data\lat.txt”、“r”)
对于文件中的y,在.read()中拆分(“\n”):
横向附加(y)
文件_in.close
lon=[]
文件_in=open(“C:\Users\applicated\Desktop\SPIE Analysis\Data\lon.txt”、“r”)
对于文件中的y,在.read()中拆分(“\n”):
lon.append(y)
文件_in.close
#---------------------------------------------------------------------------
lp=0
y1=2002
打印y1
os.chdir(“F:\\wget\\rename”)
对于glob.glob(“*.tif”)中的文件:
b=[]
b=列表(文件)
c=文件
a=[b[0],b[1],b[2],b[3]]
d=[b[4],b[5],b[6]]
年份=整数(''.join(a))
日=整数(''.join(d))
dif=2002年
如果一年=y1:
打印“”
印刷年
如果(第一年)%4==0:
lp=lp+1
y1=年
其他:
sys.stdout.write(“>”)
r=日+dif*365+lp+3
对于范围(0274)内的i:
u0=float(os.popen('gdallocationinfo-valonly-wgs84%s%s%s'(c,(lon[i]),lat[i])).read())

如果我写了这个小代码段,我希望它能工作。我建议您使用
pandas
库而不是
openpyxl
,因为它更易于操作。我还对代码进行了一些修改和优化,使之更符合当今的标准和python 3

import math,os,sys,glob
import gdal
import pandas as pd
import numpy as np
#---------------------------------------------------------------------------
# newer version of doing things
with open("C:\Users\APPLIED\Desktop\SPIE Analysis\Data\lat.txt", "r") as file_in:
    lat = [y for y in file_in.read().split("\n")]

with open("C:\Users\APPLIED\Desktop\SPIE Analysis\Data\lon.txt", "r") as file_in:
    lon = [y for y in file_in.read().split("\n")]
#---------------------------------------------------------------------------
lp = 0
y1 = 2002
print(y1)
os.chdir("F:\\wget\\Renamed")
data_dict = {}
for file in glob.glob("*.tif"):
    year = int(file[:4]) # you can slice strings and convert them to int like this 
    day = int(file[4:7]) # string is a vector of chars so you can just slice it
    dif = year - 2002
    if year != y1:
        print("")
        print(year)
        # In python if something == 0 and if something is False (not True) is equivalent
        if not (year - 1) % 4:
            lp = lp + 1
        y1 = year
    else:
        print(">")
    r = day + dif * 365 + lp + 3
    arr = np.zeros((1, 274))
    for i in range(274):
        u0 = float(os.popen('gdallocationinfo -valonly -wgs84 %s %s %s' % (file, (lon[i]), lat[i])).read())
        if u0 < 0:
            if u0 == -9999:
                val_to_write = u0
            else:
                val_to_write = 0
        else:
            val_to_write = u0/1000

        arr[i] = val_to_write
    data_dict[r] = arr

# we construct a pandas dataframe out of the dictionary
df = pd.DataFrame.from_dict(data_dict, orient='index')

# I'm not sure whether all r indices will be consecutive or will some values be missing
# In the latter case we will reindex the data frame, missing rows will be added and filled with NaN
# We're creating a new Index from 0 to whatever is the maximum key value in the dictionary, +1
df = df.reindex(pd.Index(np.arange(0, max(data_dict, key=int) + 1))) # only if indices are missing, e.g. 0,2,8,9

# Finally we're saving the dataframe to xlsx file
writer = pd.ExcelWriter('C:\Users\APPLIED\Desktop\SPIE Analysis\Data\Data1.xlsx')
df.to_excel(writer, 'Sheet1', index=False, header=False, startcol=2)
writer.save()
导入数学、操作系统、系统、全局
导入gdal
作为pd进口熊猫
将numpy作为np导入
#---------------------------------------------------------------------------
#做事的新版本
打开(“C:\Users\applicated\Desktop\SPIE Analysis\Data\lat.txt”、“r”)作为文件,位于:
lat=[y代表文件中的y\u in.read().split(“\n”)]
打开(“C:\Users\applicated\Desktop\SPIE Analysis\Data\lon.txt”、“r”)作为文件,位于:
lon=[y代表文件中的y.\u in.read().split(“\n”)]
#---------------------------------------------------------------------------
lp=0
y1=2002
打印(y1)
os.chdir(“F:\\wget\\rename”)
数据_dict={}
对于glob.glob(“*.tif”)中的文件:
year=int(文件[:4])#您可以像这样分割字符串并将其转换为int
day=int(文件[4:7])#string是一个字符向量,因此您可以对其进行切片
dif=2002年
如果是一年!=y1:
打印(“”)
印刷品(年)
#在python中,如果某物==0且某物为False(非True),则等价
如果不是(第1年)%4:
lp=lp+1
y1=年
其他:
打印(“>”)
r=日+dif*365+lp+3
arr=np.零((1274))
对于范围内的i(274):
u0=float(os.popen('gdallocationinfo-valonly-wgs84%s%s%%(文件,(lon[i]),lat[i])).read())
如果u0<0:
如果u0==-9999:
val_to_write=u0
其他:
val_to_write=0
其他:
val_to_write=u0/1000
arr[i]=val_to_write
数据记录[r]=arr
#我们用字典构造了一个数据框架
df=pd.DataFrame.from_dict(data_dict,orient='index')
#我不确定所有的r指数是连续的还是缺少一些值
#在后一种情况下,我们将重新索引数据帧,缺失的行将被添加并用NaN填充
#我们正在创建一个从0到字典中最大键值+1的新索引
df=df.reindex(pd.Index(np.arange(0,max(data_dict,key=int)+1))#仅当缺少索引时,例如0,2,8,9
#最后,我们将数据帧保存到xlsx文件
writer=pd.ExcelWriter('C:\Users\applicated\Desktop\SPIE Analysis\Data\Data1.xlsx')
df.to_excel(编写器“Sheet1”,索引=False,标题=False,startcol=2)
writer.save()

f1
的目的是什么?它是您从中读取信息或将结果保存到的文件吗?是的,我将数据保存到f1,它是excel工作表。我甚至尝试将数据保存到文本文件,但问题仍然存在。是否在每次迭代
glob.glob
后保存工作簿?这是故意的吗?事实上,我试图在所有迭代完成后保存,但ram仍在增加,所以我迭代了保存,以便可以在其间手动停止并重新启动系统以释放ram,并从停止的位置开始。这可能是我的计算机RAM管理的问题吗?非常感谢。我将运行代码并让您知道结果。如果它有效,请不要忘记接受我的答案并投票