简体   繁体   English

在Python中同一目录中的多个文件进行循环

[英]For-loop over multiple files in same directory in Python

So I already tried to check other questions here about (almost) the same topic, however I did not find something that solves my problem. 因此,我已经尝试在这里检查(几乎)同一主题的其他问题,但是我没有找到解决我问题的方法。

Basically, I have a piece of code in Python that tries to open the file as a data frame and execute some eye tracking functions (PyGaze). 基本上,我在Python中有一段代码试图将文件作为数据框打开并执行一些眼睛跟踪功能(PyGaze)。 I have 1000 files that I need to analyse and wanted to create a for-loop to execute my code on all the files automatically. 我有1000个文件需要分析,并想创建一个for循环以自动对所有文件执行代码。

The code is the following: 代码如下:

os.chdir("/Users/Documents//Analyse/Eye movements/Python - Eye Analyse")

directory = '/Users/Documents/Analyse/Eye movements/R - Filtering Data/Filtered_data/Filtered_data_test'

for files in glob.glob(os.path.join(directory,"*.csv")):
    #Downloas csv, plot 
    df = pd.read_csv(files, parse_dates = True)
    #Plot raw data
    plt.plot(df['eye_x'],df['eye_y'], 'ro', c="red")
    plt.ylim([0,1080])
    plt.xlim([0,1920])
    #Fixation analysis 
    from detectors import fixation_detection 
    fixations_data = fixation_detection(df['eye_x'],df['eye_y'], df['time'],maxdist=25, mindur=100)
    Efix_data = fixations_data[1]
    numb_fixations = len(Efix_data) #number of fixations
    fixation_start = [i[0] for i in Efix_data] 
    fixation_stop = [i[1] for i in Efix_data] 
    fixation = {'start' : fixation_start, 'stop': fixation_stop}   
    fixation_frame = pd.DataFrame(data=fixation)
    fixation_frame['difference'] = fixation_frame['stop'] - fixation_frame['start']
    mean_fixation_time = fixation_frame['difference'].mean() #mean fixation time 
    final = {'number_fixations' : [numb_fixations], 'mean_fixation_time': [mean_fixation_time]} 
    final_frame = pd.DataFrame(data=final)
    #write everything in one document
    final_frame.to_csv("/Users/Documents/Analyse/Eye movements/final_data.csv")

The code is running (no errors), however : it only runs for the first file. 代码正在运行(没有错误),但是:它仅对第一个文件运行。 The code is not ran for the other files present in the folder/directory. 没有为文件夹/目录中存在的其他文件运行该代码。 I do not see where my mistake is? 我看不出我的错误在哪里?

Your output file name is constant, so it gets overwritten with each iteration of the for loop. 您的输出文件名是常量,因此每次for循环迭代都会覆盖它。 Try the following instead of your final line, which opens the file in "append" mode instead: 请尝试以下操作,而不是最后一行,它以“附加”模式打开文件:

#write everything in one document
with open("/Users/Documents/Analyse/Eye movements/final_data.csv", "a") as f:
    final_frame.to_csv(f, header=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM