检查csv文件是否存在,并满足条件?

时间:2020-08-28 03:01:35

标签: python pandas csv operating-system

嗨,我正在处理csv文件,并且我有一个数据,我想将这些数据附加到csv文件中。但是首先,我想检查csv文件是否存在(如果为TRUE),然后只需打开csv文件并将数据附加到csv文件并保存,如果不是仅创建一个DataFrame并使用这些数据并保存它。 注意:我有一个csv文件,我想将数据样本附加到我的csv文件中 预先感谢。

这是我的尝试。

#sample of data
ID = 5
img_Latitude = 38786454
img_Longitude = 1118468

meta_lat = 45778 
meta_long = 886556 

#create a function
def create_csv( ID, img_Latitude, img_Longitude,meta_lat, meta_long):
#check if the file is exists, if True
    if os.path.isfile('C:/My/Path/compare_coordinates.csv'): 
#read the csv file  
        df = pd.read_csv('compare_coordinates.csv')
#make pd.series
        data = pd.Series([ID, img_Latitude, img_Longitude, meta_lat, meta_long], 
                 index=['ID', 'img_Latitude', 'img_Longitude', 'meta_lat','meta_long'])
#append the data to df
        df.append(data, ignore_index=True)
        
    else:
        data = [ID, img_Latitude, img_Longitude, meta_lat, meta_long]
        columns = ['ID', 'img_Latitude', 'img_Longitude', 'meta_lat','meta_long']
        df = pd.DataFrame(data, columns).T
    df.to_csv('C:/My/Path/compare_coordinates.csv', index=False)



2 个答案:

答案 0 :(得分:1)

df.append(data, ignore_index = True)行必须为:

df = df.append(data, ignore_index = True)

这是因为DatFrame.append返回带有附加行的新DF,而不是就地附加:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

答案 1 :(得分:0)

要获取所需的值,必须将其保存在变量中,以便该行 df.append(data, ignore_index = True)要编辑为df = df.append(data, ignore_index = True)并获取文件的值,是否存在以下代码:

def create_csv( ID, img_Latitude, img_Longitude,meta_lat, meta_long):
    Path = os.path.isfile('My/path/compare_coordinates1.csv')
    if Path==True:
        df = pd.read_csv('compare_coordinates1.csv')
        data = pd.Series([ID, img_Latitude, img_Longitude, meta_lat, meta_long], 
                         index=['ID', 'img_Latitude', 'img_Longitude', 'meta_lat','meta_long'])
        df = df.append(data, ignore_index=True)
        
    else:
        data = [ID, img_Latitude, img_Longitude, meta_lat, meta_long]
        columns = ['ID', 'img_Latitude', 'img_Longitude', 'meta_lat','meta_long']
        df = pd.DataFrame(data, columns).T
    df.to_csv('My/path/compare_coordinates1.csv', index=False)