How to convert users input to file path in Python - linux

I am currently trying to get the file_path (suppose ~/hello_world/) as user input and list all the files inside this directory. I can do this exact same thing if I pass ~/hello_world as sys.argv however, I can't seem to get it work if I take it as an input. I am trying to work the code from any directory and user inputted file path will be from /home/ubunut/...
Here's my working code as sys.argv:
This code is intended for unix based os only for now.
if len(sys.argv) == 2:
path = sys.argv[1]
files = os.listdir(path)
for name in files:
print(name)
Here's the code I am trying to work with:
path = input("file_path: ")
files = os.listdir(path)
for name in files:
print(name)
This is when it crashed with the following error:
Traceback (most recent call last):
File "test.py", line 14, in <module>
files = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '~/hello_world/'
Thanks in advance.

You need to expand the ~ like in the answer to this question
The following worked for me
import os
path = input("enter filepath: ")
for f in os.listdir(os.path.expanduser(path)):
print(f)

Related

Iterating through directory error: FileNotFoundError: [Errno 2] No such file or directory

I wrote a script to iterate through multiple text files in a directory and count the words contained in each that are also contained in a dictionary file. I wrote and tested the script with two files in the directory, and got it working perfectly, the script spits out two accurate integers, one for each file. However, once I add new files to the directory, I get a FileNotFound error. The file is definitely in there! Can anyone tell me what it is about the code that is causing this? I've gone through various other such posts on StackOverflow with no success. The newly added file has all the same properties as the existing two.
Code (word_count_from_dictionary-iterating.py):
import os
import sys
import nltk
nltk.download()
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import io
files_path = sys.argv[1]
textfile_dictionary = sys.argv[2]
for filename in os.listdir(files_path):
if filename.endswith(".txt"):
#accessing file for processing
file = open(filename, "rt")
text = file.read()
#tokenize text file
tokens = word_tokenize(text)
#remove non-alphabetical characters
words = []
for word in tokens:
if word.isalpha():
words.append(word)
#remove stopwords
stop_words = stopwords.words("english")
words_without_stops = []
for w in words:
if not w in stop_words:
words_without_stops.append(w)
#lemmatize remaining tokens and print
lemmatizer = WordNetLemmatizer()
lemmas = []
for x in words_without_stops:
lemmatizer.lemmatize(x)
lemmas.append(x)
#turn dictionary held in text file into a list of tokens
file = io.open(textfile_dictionary, mode="r", encoding="utf8")
dictionaryread = file.read()
dictionary = dictionaryread.split()
#count instances of each word in dictionary in the novel and add them up
word_count = 0
for element in dictionary:
for lemma in lemmas:
if lemma == element:
word_count = word_count + 1
print(word_count)
Results on command line with just two test files in the directory:
c#Computer:~/Dropbox/programming/first_project$ python3 word_count_from_dictionary_iterating.py directoryaddress dictionary.txt
showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml
241
229
Results after adding a new file (newfile.txt) to the directory:
c#Computer:~/Dropbox/programming/first_project$ python3 word_count_from_dictionary_iterating.py directoryaddress happy_words.txt
showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml
241
229
Traceback (most recent call last):
File "word_count_from_dictionary_iterating.py", line 17, in <module>
file = open(filename, "rt")
FileNotFoundError: [Errno 2] No such file or directory: 'newfile.txt'
If I run ls on the directory, the file is showing up. If I apply the script, adjusted without the iterating loop, to newfile.txt, it works. But it's just not working when looping through the directory.
Any help appreciate, I am new to programming.
The issue is when you run file = open(filename, "rt"), it is looking for filename in the directory where you started Python (~/Dropbox/programming/first_project/), but you want it to read ~/Dropbox/programming/first_project/directoryaddress.
To ensure you reading the right file, you should either pass in the full path of it as filename or, if you know you will always find it in some subdirectory, simply prepend the path to filename before trying to read it file = open(files_path+"/"+filename, "rt") (there are cleaner ways to combine paths, like the standard library pathlib).

How to randomly copy the contents of a text document to my clipboard

This is my original question
The following script copies the text in /home/my_files/document1.txt to my clipboard.
import pyperclip
path = '/home/my_files/document1.txt'
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Let's say /home/my_files/ contains the following five documents:
/home/my_files/document1.txt
/home/my_files/document2.txt
/home/my_files/document3.txt
/home/my_files/image1.jpg
/home/my_files/image2.png
I would like to create a script to randomly copy the contents of one of the three text documents in /home/my_files/ to my clipboard.
Of course the following script does not work but it shows some of the modules I've been experimenting with.
import glob,random,pyperclip
pattern = "*.txt"
path = random.choice((glob.glob(pattern))("/home/my_files/"))
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Do you have any relevant suggestions for me?
I added the subsequent content to my original question above
When I tried the following solution which #Jacob Lee created...
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())
I received the following error message...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
Someone else suggested the following script to me...
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
But that script doesn't work either. I received the following error when I ran that script...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
I am confused.
The following successfully copies the entire contents of a random text file in /home/my_files/ to my clipboard
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Thanks to #Asocia
Thanks to #Asocia for insisting that the script above works correctly. I don't know what I had been doing wrong, but I must have been doing something wrong when I indicated the script above did not work properly.
You're code raises a TypeError: 'list' object is not callable exception when you try to assign path, in this line:
path = random.choice((glob.glob(pattern))("/home/my_files"))
glob.glob() returns a list (possibly empty). (Also, you put the glob.glob() call inside redundant parentheses.) Then, you try to call glob.glob()("/home/my_files/") (in essence, [...](), raising the TypeError exception.
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files/*.txt")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())

Error when trying to create a file in a path containing parentheses with Python

Can anyone spot why this is failing?
import pathlib
from shlex import quote
path = 'testdir(abc)/subdir(123)'
filename = 'test'
content = \
"""hello
world
"""
pathlib.Path(path).mkdir(mode=0o770, parents=True, exist_ok=True)
md5_filename = quote(str(pathlib.Path(path) / (filename + '.txt')))
with open(md5_filename, 'w') as f:
f.write(content)
I'm getting this traceback
(tools) $ python test_filemake.py
Traceback (most recent call last):
File "test_filemake.py", line 13, in <module>
with open(md5_filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: "'testdir(abc)/subdir(123)/test.txt'"
I think I don't understand posix paths well enough to understand what's going on. If I take the parentheses out of the directory names in the path, it works fine. shlex.quote() is adding the extra layer of double quotes, which seems to be breaking things.

Python File Check and Creation

I am trying to check or create a directory and I am getting this error:
/usr/bin/python3.6 /home/user/Development/americas.py Traceback (most
recent call last): File "/home/dquezada/Development/americas.py",
line 23, in
os.mkdir(path) FileNotFoundError: [Errno 2] No such file or directory: '/home/dquezada/Development/data/maps/americas/'
Process finished with exit code 1
Below is my code:
path = '/home/user/Development/data/maps/americas/'
# Check if path exists, if it does not it creates it
if not os.path.exists(path):
os.mkdir(path)
wm.render_to_file(path + timeStamp + '_americas.svg')
I believe os.path.isdir(path) is what you are looking for.
This will return True if it is a directory, or False if it isn't.
os.path.exists(path) is not intended for what you are using it for.
path = '/home/user/Development/data/maps/americas/'
# Check if path exists, if it does not it creates it
if not os.path.isdir(path):
os.mkdir(path)
wm.render_to_file(path + timeStamp + '_americas.svg')
That should work for you.

python : how to use wave module?

when I try the following program :
import wave
w = wave.open('f.wav', 'r')
for i in range():
frame = w.readframes(i)
the following error comes :
Traceback (most recent call last):
File "F:/Python31/fg.py", line 2, in <module>
w = wave.open('f.wav', 'r')
File "F:\Python31\lib\wave.py", line 498, in open
return Wave_read(f)
File "F:\Python31\lib\wave.py", line 159, in __init__
f = builtins.open(f, 'rb')
IOError: [Errno 2] No such file or directory: 'f.wav'
can u tell me wat could b the reason ???
The file is not in the path you put that Python interpreter can find. Check that f.wav is in the same path of your script (or chance the path in open).
Is not a wave issue at all.
You are running the python script from a directory where no file f.wav exists. It can't find the file to read. Either copy f.wav to that directory or run you script from the directory f.wav is located in.

Resources