Hello I was just wondering if it was possible to open multiple predefined text files in python.
I have some code below (it doesn't work yet), and the first function has a parameter of categories, which are all text file names that are predefined below in a te开发者_C百科st case. I need to try and open all of the text files as defined below to input them into an sql database.
data_entry(categories):
with open ((categories)"*.txt"), "r") as categories:
lines = categories.readlines()
for line in lines:
data = line.split()
number = data[0]
value = data[1]
cursor.execute("""INSERT INTO popularity (PersonNumber, category, value)
VALUES(%s, %s, %s)""", (number, category, value))
if __name__ == '__main__':
data_entry(['movies', 'sports', 'actors', 'tv', 'games', \
'activities', 'musicians', 'books'])
Is this possible? If so, how would I go about getting this to work how I need?
Thank you in advance!
Use string interpolation or formatting to put the category into the filespec, and glob.glob()
to resolve it.
Why are you reading the lines into a list, and then going over it after the fact?
import glob, itertools
def data_entry(categories):
globs = [glob.iglob(category + "*.txt") for category in categories]
for filename in itertools.chain(*globs):
with open(filename) as f:
for line in f:
number, value = line.split()
cursor.execute(...)
itertools.chain
; glob
; list comprehensions
Python is not Perl, so you should write code that is easier to read, even if is a little bit longer. Also the the new with syntax is available only on newer pythons.
You should be able to adapt this sequence to your code
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print(file)
Or just:
data_entry(categories):
foreach category in categories:
f = open ("%s.txt" % (category)), "r")
精彩评论