How to read multiple txt file from a single folder in Python? [duplicate]
2024/11/16 3:18:51
How can I read multiple txt file from a single folder in Python?
I tried with the following code but it is not working.
import globimport errnopath = '/home/student/Desktop/thesis/ndtvnews/garbage'files = glob.glob(path)for name in files:try:with open(name) as f:print namefor line in f:print line,f.close()except IOError as exc:if exc.errno != errno.EISDIR:raise
Answer
Your glob isn't correct. You should add a /* to the end of your path to select all files (or directories) in your path, and then check if they are files with os.path.isfile. Something like:
from os.path import isfile
files=filter(isfile,glob.glob('%s/*'%path))
You also have an issue with the actual opening. When your with statement ends, the file is closed and f is no longer accessible. Anything you do with the file should be under the with statement. And you shouldn't explicitly close it.
The following code works fine as long as the time in the spinbox does not change. What I want is to do the set the time for a break. The first time it works perfectly but after that if I change the val…
I am lazy and want to avoid this line in every python file which uses logging:logger = logging.getLogger(__name__)In january I asked how this could be done, and found an answer: Avoid `logger=logging.g…
Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 8…
Lets assume that we have nested python dictionaries which should be written in single excel sheet file.
Following are sample dictionaries which can be used.
Car = [{"carbmodel": "Model A…
Requirement :
1.create a gui using Tkinter
2.Update the excel by fetching values from Tkinter entry widget
3.Read another sheet of the same workbook
4.plot graph using inside the Tkinter window.Prob…
I have a pandas dataframe with timestamps shown below:6/30/2019 3:45:00 PMI would like to round the date based on time. Anything before 6AM will be counted as the day before. 6/30/2019 5:45:00 AM -&g…
Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…
I am trying to create a function in python which will display the date. So I can see the program run, I have set one day to five seconds, so every five seconds it will become the next day and it will p…
This question already has answers here:How to determine the IP address of the server after connecting with urllib2?(4 answers)Closed 9 years ago.Im terribly sorry if this is unacceptable or answered e…
Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…