简体   繁体   中英

How to plot multiple CSV files in a folder using python

Let's say I have multiple CSV files which all have their x and y coordinates start from row 15 in their own columns of 1 and 2. I just want to run through all the CSV files in a folder running this script and just plotting x and y.

My idea so far is using glob in the current directory and importing panda so that I may be able to use ".read_csv".

However, I'm not too sure on how to set up the for loop which will be required to run through all the .csv files

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
headers = ['x', 'y']
df = pd.read_csv('C:\Users\User1\Downloads\DataLog.CSV',names=headers)
print (df)

# plot
plt.plot(x,y)
plt.show()

That's what I have so far just to get it working on a single file. However, running this yields an error.

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \\UXXXXXXXX escape

This is very unspecific, so I can only give you a general example of how I usually do it and you'll have to figure out the errors occuring from your specific case yourself.

from glob import glob
import pandas as pd
import matplotlib.pyplot as plt

All_files = glob('*.csv')
headers = ('x','y')


for file in All_files:

    name = file.split('.csv')[0]

    df = pd.read_csv(file,
                      names=headers,
                      skiprows=15)

    x,y = df['x'], df['y']

    fig, ax = plt.subplots(figsize=(7,4))

    ax.plot(x,y)


    plt.tight_layout()
    plt.savefig(name+'.png', dpi=300, bbox='tight')

The unicode error occurs, because you specified your file path without a 'r' at the start. Strings in python often need to be declared as 'raw' strings so that they don't get misinterpreted. Your filepath: 'C\\users\\...' contains a '\\u\u0026#39;, which is interpreted as a unicode escape character. In python you either have to declare string literals with a leading '\\', or put an r in front of it so: 'C\\\\users\\\\...' or r'C\\users\\...'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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