0
if os.path.exists('D:\Python\New folder\'+f):
 open(f+c, 'w')

The f is a character that changes in a loop. How do i add it to the rest of the 'D:\Python\New folder\' ? What i've done above makes the whole line highlighted as a comment.

asked Apr 30, 2015 at 18:09
1
  • Read up on raw strings and os.path.join Commented Apr 30, 2015 at 18:11

3 Answers 3

3

You cannot use a \ backslash as the last character, as \' means use an actual quote character rather then the end of the string.

You should really use os.path.join() here and have Python join the path and the filename together, and use a raw string literal for the path so that the other \ characters don't form escape sequences (\n would be a newline, for example):

path = os.path.join(r'D:\Python\New folder', f)
if os.path.exists(path):
 open(os.path.join(path, c), 'w')

os.path.join() will add the required \ path separators for you.

answered Apr 30, 2015 at 18:11
Sign up to request clarification or add additional context in comments.

Comments

0

Use python os.path module

os.path.join

answered Apr 30, 2015 at 18:11

Comments

0

Try:

if os.path.exists('D:\Python\New folder\\'+f):
 open(f+c, 'w')
answered Apr 30, 2015 at 18:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.