Avatar of csehz
csehz
Flag for Hungary asked on

Python - adding variable inside a string

Dear Experts,

Actually having the following Python code to import .csv file and it works fine:

import csv

with open(r"C:\File.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    

Open in new window


I would like to restructure a little bit with adding the path to a variable as FilePath and using that in the open command, around like this (it does not work of course in this format)

import csv

FilePath = "C:\File.csv"

with open(r % FilePath) as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    

Open in new window


Could you please advice about the Python syntax including a variable like that?

Thanks in advance,
Python

Avatar of undefined
Last Comment
Subodh Tiwari (Neeraj)

8/22/2022 - Mon
Subodh Tiwari (Neeraj)

This should work...

with open(FilePath) as csvfile:

Open in new window

csehz

ASKER
@Neeraj thanks for the advice, with that syntax getting the following error message:

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

Presumably that 'r' sign should be somehow added at the beginning as it is in the format of

with open(r"C:\File.csv") as csvfile:

Open in new window

SOLUTION
Subodh Tiwari (Neeraj)

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
pepr

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
csehz

ASKER
@pepr thanks a lot for the explanation, it works of course like that
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Subodh Tiwari (Neeraj)

Didn't I offer the same solution? :)
csehz

ASKER
@Neeraj oops you are right just when came in the morning did not catch that you also answered :(

Sorry again as you again did not get the well deserved points (as we spoke I caused that you did not got all the 1000 in the other thread) :(
Subodh Tiwari (Neeraj)

Never mind. :)
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.