0

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

2
  • 1
    Hello! The idea seems correct. Try to implement it, and come back if you have an error, showing your code and the error traceback. Stackoverflow is not a free coding service: as it is, this question is too broad. Commented Sep 18, 2019 at 17:03
  • Thank you, I updated with the code I've been tampering around with. Commented Sep 18, 2019 at 19:39

1 Answer 1

1

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', 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\...'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.