1

I have some filenames in a directory, all named like '.\subreddits\somename\somename.db'.
One of these files has a number following the backslashes:

.\subreddits\600euro\600euro.db

I want to
* iterate through all files in the dir,
* get the middle element/or last element of each filename
* open the file, ie open an sql connection to it.

I cannot split the filename of that one file with the numbers after the backslashes:

for db in os.listdir(dir_with_dbs):
    print(db) # .\subreddits\600euro\600euro.db -> .\subredditsƀeuroƀeuro.db
    # get middle name of db file: .\subreddits\xy\xy.db -> xy
    # THIS FAILS on the backslash-number combination:
    out_str = db.split("\\")[2] # list index out of range

    # open file that will contain results: query_res_xy
    with open("query_res_" + out_str, 'w') as out:

        #execute a query on the db file
        conn = sqlite3.connect(os.path.join(dir_with_dbs, db))          
        c = conn.cursor()
        c.execute(query)

        # write results of query to file with same middle/last name
        for row in c.fetchall():
            out.write(row + '\n')

This question How to manage a path with numbers after backslashes? describes a similar problem, but OP didn't want to change/split the string.
I cannot rename the files and I do not know beforehand which files are in the dir.

How can I get python to recognize the backslashes even when numbers come after them? Or how else could I get the middle/last element of the filenames?

I have also tried to encode() + decode() the filenames, but I cannot retrieve the numbers in the string.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Anushka--x
  • 960
  • 9
  • 9
  • *always* use the generic [python] tag – juanpa.arrivillaga Dec 23 '17 at 21:29
  • 1
    I cannot reproduce this problem. I suspect that you are defining the paths/filenames with literal strings (maybe for testing) and did not escape the backslashes, which would mean that `\6` is not a backslash followed by a 6, but the single character with ASCII code 6. – trincot Dec 23 '17 at 21:47
  • Agree with @trincot here. I created a file in a directory called "\subreddits\600euro\600euro.db" and when found via `os.listdir` Python will escape the backslashes so that it looks like `\\subreddits\\600euro\\600euro.db`. Without the escaping, Python is interpreting the "\600" to be a special character (which in this case is the [lower case latin b](https://www.utf8icons.com/character/384/latin-small-letter-b-with-stroke)). – TheF1rstPancake Dec 23 '17 at 22:41
  • @trincot You are right. I did it in the pyshell and set the paths manually. I tried it again on the whole dir and that works. – Anushka--x Dec 27 '17 at 18:40

0 Answers0