This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 5 years ago.
I am fairly new in python and I am writing a python script that can read json files from a directory and work on it. For that purpose, I am asking the user about the file name.
file_dir = input("Please enter the directory COMPLETE path where all dialog json files are placed: ")
files = listdir(str(file_dir))
However, I get the error when I enter the path.
Please enter the directory COMPLETE path where all dialog json files are placed: /Users/monideepde/Documents/Sanofi/EnglishDialogs
Traceback (most recent call last):
File "/Users/monideepde/PycharmProjects/KoreDialogLanguageConverter/Converter.py", line 4, in <module>
file_dir = input("Please enter the directory COMPLETE path where all dialog json files are placed: ")
File "<string>", line 1
/Users/monideepde/Documents/Sanofi/EnglishDialogs
^
SyntaxError: invalid syntax
Process finished with exit code 1
Strangely, this error is not seen when I wrap my path in double-quotes. If anyone understands why I am getting this error can you please share it with me?
P.S: I am using python 2.7
Thanks
In Python 2.x, input() tries to run the input as a Python expression. Use raw_input() instead - it returns a string without evaluation
file_dir = raw_input("Please enter the directory COMPLETE path where all dialog json files are placed: ")
Try raw_input instead of input since you are using python2.7. raw_input("enter the directory").
And for working with directories check out the os module.
Related
I was trying a very simple code on my MacBook: here is the code
def file_name(fname):
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
quit()
count = 0
starts_with = **input**('Entries starts with: ')
for line in fhand:
if line.startswith(starts_with):
count = count + 1
print('There were ', count, ' subject lines in', fname)
fname = input('Enter the file name: ')
file_name(fname)
In order for that code to work, I had to replace input() with raw_input(). I have installed python 3.8 on my device though cannot run the code with it. At first, I thought the problem was with VS code. After switching to PyCharm professional I still have the same, exact problem.
The desired output after renaming to raw_input() is:
Hou-Pengs-MBP:PY4E houpengzhu$ python File.py
Enter the file name: hw.py
Entries starts with: print
('There were ', 1, ' subject lines in', 'hw.py')
Output when using input()
Hou-Pengs-MBP:PY4E houpengzhu$ python File.py
Enter the file name: hw.py
Traceback (most recent call last):
File "File.py", line 15, in <module>
fname = input('Enter the file name: ')
File "<string>", line 1, in <module>
NameError: name 'hw' is not defined
My configuration for PyCharm:
PyCharm, click to view screenshot
for VS code:
VS code, click to view screenshot
What should I do to yield the desired result?
UPDATE: I dug around and found this solution from Ryosuke Hujisawa (second upvoted answer) worked for me: how to change default python version?
Now my default version of python has been changed to python 3.
When running that code, you still need to state you want python3 to IDE but doing so you won't need use raw_input() from python 2 anymore for the code to work.
Your IDE doesn't control your terminal session. python -V will show you what the problem is, or more precise, the version you're executing the script with
You should try to run /usr/bin/python3 hw.py, for example for python 3.7.3 or with /usr/local/bin/python3 for 3.8.3
Or you need to activate your venv then you can just use python
Are you sure that you are running it on python 3.In python 3 there is no raw_input()
It should work with input() if you use python3 File.py.
I have written a python program that uses values from text files. In order to get the text files, one of the requirements is that it must be able to accept the file path as an argument in the terminal. I am trying to use:
# -*- coding: utf-8 -*-
import numpy
x = str(input("Enter directory path: \n"))
data = numpy.loadtxt(open(x), int)
However , when I run the program in the terminal like this:
MBP:Game test$ python GameOfLife.py
Enter directory path:
/Users/test/Google Drive/Game.py
I get the following error afterwards.
Traceback (most recent call last):
File "Game.py", line 5, in <module>
x = str(input("Enter directory path\n"))
File "<string>", line 1
/Users/test/Google Drive/Game.py
^
SyntaxError: invalid syntax
I am new to python, so any help would be really great.
string must be put in quotes;
Try this:
"/Users/test/Google Drive/Game.py"
In addition you can use function raw_input instead of input. input function run your input text as python code but with raw_input you could input anything without any constraints.
so you can use
x = raw_input("Enter directory path: \n")
instead of
x = str(input("Enter directory path: \n"))
This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 7 years ago.
I'm a Python newbie and I get the following error for the code...
name = input("What's your name? ")
print(name)
Output:
G:\Code\Python>UserInput.py
What's your name? Jeremy
Traceback (most recent call last):
File "G:\Code\Python\UserInput.py", line 3, in <module>
name = input("What's your name? ")
File "<string>", line 1, in <module>
NameError: name 'Jeremy' is not defined
The code gets executed only if I replace the input() as raw_input... How do I get it to display the message just by including the input()? I get that it has got something to do with the Python Interpreter versions (I've got both python27 and python34 installed). How do I go on about that??
You shouldn't be using input, it is equivalent to eval(raw_input(prompt)) which will try to execute your input.
https://docs.python.org/2/library/functions.html#input
Use raw_input instead.
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 7 months ago.
I am trying to read a text file on my hard drive via python with the following script:
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
But it is giving the following error:
IOError Traceback (most recent call last)
<ipython-input-2-4f422ec273ce> in <module>()
----> 1 fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
IOError: [Errno 2] No such file or directory: 'H:\\CloudandBigData\x0cinalproj\\BeautifulSoup\twitter.txt'
I also tried with other way:
with open('H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt', 'r') as f:
print f.read()
Ended up with the same error. The text file is present in the directory specified.
Replace
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
with
fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
Here, I have created a raw string (r""). This will cause things like "\t" to not be interpreted as a tab character.
Another way to do it without a raw string is
fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")
This escapes the backslashes (i.e. "\\" => \).
An even better solution is to use the os module:
import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')
This creates your path in an os-independent way so you don't have to worry about those things.
One last note... in general, I think you should use the with construct you mentioned in your question... I didn't in the answer for brevity.
I was encountering same problem. This problem resulted due to different file path notation Python.
For example, filepath in Windows reads with backward slash like: "D:\Python\Project\file.txt"
But Python reads file path with forward slash like: "D:/Python/Project/file.txt"
I used r"filepath.txt" and "os.path.join" and "os.path.abspath" to no relief. os library also generates file path in Windows notation. Then I just resorted to IDE notation.
You don't encounter this error if "file.txt" is located in same directory, as filename is appended to working directory.
PS: I am using Python 3.6 with Spyder IDE on Windows machine.
Is there a simple module that let's you paste input in python ?
Asking someone to type letter by letter is kinda harsh .
By default a .py file is opened with python.exe if is installed and this does not allow "rightclick+paste" in the console .So how can i make this happen with python ? i think this would be more of a exact question .
You can make this by open cmd.exe and type here "C:\Python32\python".
Path is depend on the version of python. Mine is 3.2.
If you're looking for a way to simply paste something into the windows command prompt, John Giotta is correct that a user can click on the little icon in the top left.
I imagine, however, that you're looking for a way that a user can input a large amount of text, without typing it in line by line. A simple way to do this, would be to let the user input a file name, which python would then read. Perhaps something like this is what you're looking for:
while True:
filename = raw_input("Path to file to be read: ")
try:
with open(filename, 'rb') as f:
contents = f.read()
break
except IOError:
print "That was not a valid file \n"
This loop will keep asking the user for a file until then enter a valid path. When they enter a valid path, it will be read in as a string to the contents variable. This way, a user could enter a large amount of text into a file, and then you simply prompt them for the path to the file.
You can read up on file input more In the docs.