1

Below you can find a simple script to search text in files. I'm looking for how to be more crossplatform i mean how to avoid '\' in path to look through all dirs and do it with standard library from Python. Because as i know, mac use '/' instead of backslash. Any idea how to do it?

#!/usr/bin/env python    

def find(text, search_path):
    res = []

    for subdir, dirs, files in os.walk(search_path):
        for fname in files:
            if os.path.isfile(subdir + "\\" + fname):
                with open(subdir + "\\" + fname) as f:
                    for i, line in enumerate(f):
                        if text in line:
                            res.append([fname, i])
  • check `os.path.join` – kmaork Dec 21 '16 at 19:54
  • While `os.path.join` is the correct solution, Windows is perfectly happy with `/` directory separators. – kindall Dec 21 '16 at 19:58
  • So obviously answer. Thank you! – Purple Rain Dec 21 '16 at 20:18
  • @mbomb007: Purple Rain is not looking for the [`PATH` separator](https://docs.python.org/3/library/os.html#os.pathsep) (typically `':'` or `';'`), but the [_directory_ separator](https://docs.python.org/3/library/os.html#os.sep) (typically `'/'` or `'\'`). – Kevin J. Chase Dec 21 '16 at 20:55
  • See "[How/where to use `os.path.sep`?](https://stackoverflow.com/questions/32431150)", and the [accepted answer](https://stackoverflow.com/questions/16789790/4116239) from "[Differences between use of `os.path.join` and `os.sep` concatenation](https://stackoverflow.com/questions/16789714)" for better ways to handle directory separators. – Kevin J. Chase Dec 21 '16 at 21:04
  • @KevinJ.Chase I know, but in the linked question the OP says "In the discussions to this question How do I find out my python path using python? , it is suggested that `os.sep`..." and `os.sep` is presumably what he's looking for. – mbomb007 Dec 21 '16 at 21:13

2 Answers2

2

You can use os.path.join to join paths together, for example instead of

subdir + "\\" + fname

you could do

os.path.join(subdir, fname)
Midiparse
  • 4,701
  • 7
  • 28
  • 48
0

You could use os.sep. This is just showing that you can in fact get the character used by the operating system to separate pathname components if you want, but for concatenating path names, see the other answer on using os.path.join().

The character used by the operating system to separate pathname components. This is '/' for POSIX and '\\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os.path.split() and os.path.join() — but it is occasionally useful. Also available via os.path.

mbomb007
  • 3,788
  • 3
  • 39
  • 68