import os
path=r'C:\Users\User\Documents\prog'
folderlist=os.listdir(path)
def is_file_contain_word(folderlist,query_word):
for file in folderlist:
if query_word in open(folderlist).read():
print (file)
print("finishing searching.")
query_word=input("please enter the keyword:")
is_file_contain_word(folderlist,query_word)
This is what I have so far. It has returned that I have type error:
invalid file: ['1.doc', '1.odt', 'new.txt']
I got this error when I swapped path with folderlist in the open
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\God\\Documents\\prog'
import os
This is my new code:
import os
path=r'C:\Users\God\Documents\prog'
folderlist=os.listdir(path)
print(folderlist)
def is_file_contain_word(folderlist,query_word):
for i in os.listdir(path):
if query_word in i:
print("Found %s" %query_word)
else:
print("not found")
query_word=input("please enter the keyword:")
is_file_contain_word(path,query_word)
This goes through each of the 3 files to search for the filename. It only stops when it finds it or it goes through it.
You are making multiple mistakes here:
First, try to indent your code correctly:
def is_file_contain_word(folderlist,query_word):
for file in folderlist:
if query_word in open(folderlist).read():
print (file)
print("finishing searching.")
Then the real problem.
open(folderlist) should be open(file), as I believe that's your intention.
And that's one reason why the program won't run: open(folderlist) opens C:\Users\User\Documents\prog, which is a directory and will cause problem.(You probably thought this line opens all files contained in that folder)
BTW, don't use "file" as a var, it's a reserved word in python.
However, even though you fix this part, the original function still won't work.
def is_file_contain_word(folderlist,query_word):
for f in folderlist:
if query_word in open(f).read():
print (f)
print("finishing searching.")
Why? If you check this folderlist(folderlist=os.listdir(path)), it would be something like:
["Prog's Movies", "Homework3.pdf", "blahblah.txt"]
Which is problematic because first, you can't open them because they aren't absolute path(Like C:\Users\God\Documents\prog\blahblah.txt), second, listdir would also list all directories(In this case "Prog's Movies" directory), which you can't use open to open them.
At last, if you are running this on command line, don't make two folderlist vars. I know in this case it won't cause problem, but it dose reduce your code's readibility and seem to confuse you a little bit.
How to fix it?
How to list all files of a directory?
Here is a nice answer to how to open all files in a directory correctly.
Related
I'm trying to make a basic text adventure game as shown below:
import time
print ("Hello and welcome to Prison Break")
print()
print("Press S to start")
while True:
choice = input("> ")
if choice == 'S'or's' :
print("Paddy Games presents...")
time.sleep (2)
print("Prison Break!")
time.sleep(1)
print("Before we begin, lets find out a bit about how you got
stuck in this prison in the first place!")
time.sleep(2.5)
print("When you are finished reading, type finished")
file = open("Prison Break Backstory.txt","r")
file_contents = file.read()
print (file_contents)
print()
The problem is that i get this when I go to run it:
'FileNotFoundError: [Errno 2] No such file or directory'
I have checked that i have written the files name correctly, it is definitely there
Now I am aware that there are already solutions for this on the site using the exact, or absolute, path. However, I will be working on this at home on my raspberry pi 3 and also on my schools computers. The file will not be in the same place when i distribute the code. So in conclusion I need a solution that will make the file locatable on all computers regardless of where it is as long as it is there.
Sorry if this is a stupid question, I am still learning python and haven't perfected it yet.
Thank you in advance for any replies!
Do you want an example of the relative path, or searching every file in the computer? For the latter, look at this question, so you could do something like:
for root, dirs, files in os.walk("C:/Users", topdown=False):
for name in files:
if name == "Prison Break Backstory.txt":
file = open(os.path.join(root, name), "r")
But this is so incredibly inefficient I really recommend you not do this. Plus, if there happened to be two versions of this file located in different directories, it would screw stuff up.
Instead, what you should do is ensure you always know where this text file is located, relative to your python code. Say your entire project is located in C:/Users/myname/Desktop/Project, you could have your python code in C:/Users/myname/Desktop/Project/src (source), and your text file in C:/Users/myname/Desktop/Project/txtfiles. Whenever you send the "Project" folder to someone, the python code could access the text file like so:
file = open("../txtfiles/Prison Break Backstory.txt","r")
Also, make sure you always close the file at the end. It would probably be better to instead use
with open("../txtfiles/Prison Break Backstory.txt", "r") as f:
file_contents = f.read()
So you don't have to close the file/ risk not closing it and getting i/o issues.
I have a program that relies on user input to enter files for the program to open in Python 2.7.11. I have all of those files in a sub-directory called TestCases within the original directory Detector, but I can't seem to access the files in TestCases when running the program from the super-directory. I tried to use os.path.join but to of no avail. Here is my code:
import os.path
def __init__(self):
self.file = None
os.path.join('Detector', 'TestCases')
while self.file == None:
self.input = raw_input('What file to open? ')
try:
self.file = open(self.input, 'r')
except:
print "Can't find file."
My terminal when I run the program goes as follows:
>>> What file to open? test.txt # From the TestCases directory
>>> Can't find file.
>>> What file to open? ...
Am I using os.path.join incorrectly? I thought it was supposed to link the two directories so that files could be accessed from the sub-directory while running the program from the super-directory.
You are using os.path.join('Detector', 'TestCases'), that should return 'Detector/TestCases', but you aren't storing that variable anywhere.
I suppose that you are in Detector directory and you want to open files in TestCases. I that case you can use path join (It concatenates its arguments and RETURNS the result):
import os.path
file = None
while not file:
input = raw_input('What file to open? ')
try:
filepath = os.path.join('TestCases', input)
file = open(filepath, 'r')
except IOError:
print "Can't find " + input
I have stored the result of os.path.join so you could see that it doesn't change the directory, it just concatenates its arguments, maybe you was thinking that function will change the directory, you can do it with os.chdir.
Try it first in a simple script or in the terminal, it will save many headaches.
The documentation about os.path.join
Join one or more path components intelligently. The return value is the concatenation of path...
It seems like you expect it to set some kind of PATH variable or affect the current working directory. For a first start it should be sufficient to add something like this to your code:
open(os.path.join("TestCases",self.input), 'r')
I am trying to make a minor modification to a python script made by my predecessor and I have bumped into a problem. I have studied programming, but coding is not my profession.
The python script processes SQL queries and writes them to an excel file, there is a folder where all the queries are kept in .txt format. The script creates a list of the queries found in the folder and goes through them one by one in a for cycle.
My problem is if I want to rename or add a query in the folder, I get a "[Errno 2] No such file or directory" error. The script uses relative path so I am puzzled why does it keep making errors for non-existing files.
queries_pathNIC = "./queriesNIC/"
def queriesDirer():
global filelist
l = 0
filelist = []
for file in os.listdir(queries_pathNIC):
if file.endswith(".txt"):
l+=1
filelist.append(file)
return(l)
Where the problem arises in the main function:
for round in range(0,queriesDirer()):
print ("\nQuery :",filelist[round])
file_query = open(queries_pathNIC+filelist[round],'r'); # problem on this line
file_query = str(file_query.read())
Contents of queriesNIC folder
00_1_Hardware_WelcomeNew.txt
00_2_Software_WelcomeNew.txt
00_3_Software_WelcomeNew_AUTORENEW.txt
The scripts runs without a problem, but if I change the first query name to
"00_1_Hardware_WelcomeNew_sth.txt" or anything different, I get the following error message:
FileNotFoundError: [Errno 2] No such file or directory: './queriesNIC/00_1_Hardware_WelcomeNew.txt'
I have also tried adding new text files to the folder (example: "00_1_Hardware_Other.txt") and the script simply skips processing the ones I added altogether and only goes with the original files.
I am using Python 3.4.
Does anyone have any suggestions what might be the problem?
Thank you
The following approach would be an improvement. The glob module can produce a list of files ending with .txt quite easily without needing to create a list.
import glob, os
queries_pathNIC = "./queriesNIC/"
def queriesDirer(directory):
return glob.glob(os.path.join(directory, "*.txt"))
for file_name in queriesDirer(queries_pathNIC):
print ("Query :", file_name)
with open(file_name, 'r') as f_query:
file_query = f_query.read()
From the sample you have given, it is not clear if you need further access to the round variable or the file list.
I'm writing a script to save a file and giving the option of where to save this file. Now if the directory entered does NOT exist, it breaks the code and prints the Traceback that the directory does not exist. Instead of breaking the code I'd love to have have a solution to tell the user the directory they chose does not exist and ask again where to save the file. I do not want to have this script make a new directory. Here is my code:
myDir = input('Where do you want to write the file?')
myPath = os.path.join(myDir, 'foobar.txt')
try:
f = open(myPath, 'w')
except not os.path.exists(myDir):
print ('That directory or file does not exist, please try again.')
myPath = os.path.join(myDir, 'foobar.txt')
f.seek(0)
f.write(data)
f.close()
This will get you started however I will note that I think you need to tweak the input statement so the user does not have to put quotes in to not get an invalid syntax error
import os
myDir = input("Where do you want to write the file ")
while not os.path.exists(myDir):
print 'invalid path'
myDir = input("Where do you want to write the file ")
else:
print 'hello'
I do not know what your programming background is - mine was SAS before I found Python and some of the constructions are just hard to think through because the approach in Python is so much simpler without having a goto or similar statement but I am still trying to add a goto approach and then someone reminds me about how the while and while not are simpler, easier to read etc.
Good luck
I should add that you really don't need the else statement I put it there to test/verify that my code would work. If you expect to do something like this often then you should put it in a function
def verify_path(some_path_string):
while not os.path.exists(some_path_string):
print 'some warning message'
some_path_string = input('Prompt to get path')
return some_path_string
if _name_ == main:
some_path_string = input("Prompt to get path")
some_path_string = verify_path(some_path_string)
I am trying to write a detector that checks if a certain directory can be deleted using shutil.rmtree. I have a partial code finished as below that now works partial.
This code is now able to gives warning when any .exe files under the target folder is still running. But, this code is not yet able to flag warnings if any particular file under a folder is opened by an editor (which is another cause that makes a directory not deletable). Any guidance will be appreciated. Thanks in advance
Note: I've used open method to check for any locked file.
def list_locked_files(dir):
isLocked = False
for name in os.listdir(dir):
uni_name = unicode(name)
fullname = dir + u'/' + uni_name
if os.path.isdir(fullname):
list_locked_files(fullname)
else:
try:
f = open(fullname, 'r+')
f.close()
except IOError:
print fullname + u' is locked!'
isLocked = True
if isLocked is True:
print u'Please close the files/dir above !'
sys.exit(0)
It is not necessarily possible to determine whether a file deletion will succeed or fail on Windows. The file could be opened in a fully permissive share mode which means another attempt to open the file will succeed (no matter what kind of access you request).
The only way to tell whether a file can be deleted is to actually try it.
Even if there were an accurate way to tell beforehand, once you get the information it is instantly out of date. For example, after you call list_locked_files, a program could open another file in that directory which would cause rmtree() to fail.