I want to read multiply .txt file in one folder, and read every line as a list.
ID: 3573600 • Letter: I
Question
I want to read multiply .txt file in one folder, and read every line as a list.
example name of the files
example content of each file
This is my code, however it prints nothing.
I hope the resulting is like
Attr+Topic&Thing; Attribute. policy.txt Attr+Topic&Thing; Attribute. proportion.txt Attr Topic&Thing; Attribute.rate.txt Attr+Topic&Thing; Attribute. relation difference.txt Attr+Topic&Thing; ribute relation.equivalence.txt Attr+Topic&Thing; Attribute. safety.txt Attr+Topic&Thing; Attribute. stability.txt Attr+Topic&Thing; Attribute. strength.txt Attr+Topic&Thing; Attribute. structural txt Attr+Topic&Thing; Attribute tosort.cy.txt Attr+Topic&Thing; Attribute.tosort.ity.txtExplanation / Answer
If we want the output to skip empty lists then the code is as below:
import glob
import errno
path = './*.txt'
files = glob.glob(path)
for name in files:
# try:
# with open(name) as f
f = open(name, 'r')
for line in f:
words = list()
#print(line)
for word in line.split():
words.append(word)
#except IOError as exc:
# if exc.errno != errno.EISDIR:
# raise
if len(words)>0:
print(words)
If we need to output the empty line as well then the code is
import glob
import errno
path = './*.txt'
files = glob.glob(path)
for name in files:
# try:
# with open(name) as f
f = open(name, 'r')
for line in f:
words = list()
#print(line)
for word in line.split():
words.append(word)
#except IOError as exc:
# if exc.errno != errno.EISDIR:
# raise
#if len(words)>0:
print(words)
Your code has the wrong placement of print statement and rest everything is fine. The corrected version of your code is as below:
import glob
import errno
path = './*.txt'
files = glob.glob(path)
for name in files:
try:
with open(name) as f:
for line in f:
words = list()
for word in line.split():
words.append(word)
print(words)
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.