2

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]) 
6

2 Answers 2

3

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

subdir + "\\" + fname 

you could do

os.path.join(subdir, fname) 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.