Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Invalid syntax - Invalid syntax [duplicate]

I have the following piece of code to pull the names of all files within a particular folder (including all files in it's subfolders):

import sys,os

root = "C:\Users\myName\Box Sync\Projects\Project_Name"
path = os.path.join(root, "Project_Name")

for path, subdirs, files in os.walk(root):
    for name in files:
        print os.path.join(path, name)

Unfortunately, it throws the following error:

>   File "<ipython-input-7-2fff411deea4>", line 8
>     print os.path.join(path, name)
>            ^ SyntaxError: invalid syntax

I'm trying to execute the script in Jupyter Notebook. I also tried saving it as a .py file and running it through Anaconda prompt but received the same error. Can someone please point out where I'm going wrong? I'm pretty new to Python.

Thanks

like image 377
Chipmunk_da Avatar asked Dec 09 '25 03:12

Chipmunk_da


2 Answers

in python3, print function needs to be like this :

print(os.path.join(path, name))

For more information on the changes within print function from python 2 to 3, check these links :

  • print is a function
  • pep-3105
  • What is the advantage of the new print function in Python 3.x over the Python 2 print statement?
like image 127
Mohamed Ali JAMAOUI Avatar answered Dec 11 '25 16:12

Mohamed Ali JAMAOUI


This is a Python 2 Vs Python 3 issue.

In Python 2, print is used without parenthesis like:

print 42

In Python 3, print is a function and has to be called with parenthesis like:

print(42)
like image 43
Matthieu Moy Avatar answered Dec 11 '25 15:12

Matthieu Moy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!