-1

In the piece of code I have, there are many instances where I have the following line

'/home/myname/directory'

For example, I have the following lines of code

filepath = os.listdir('/home/myname/directory')

for content in filepath

   # do something

In the next part of the project, I have to share the code with some one else. I know this person runs openSUSE. If I want code to create that specific directory with the same path to the directory as mine, what do I need to include?

I know its going to involve the OS module but i am not sure which functions and methods to use.

JM9
  • 119
  • 1
  • 7
  • 1
    When you say, *"I want code to create that specific directory with the same path to the directory as mine"*, you mean you want to create `/home/jm9/my_app` (where `myname=jm9` and `directory=my_app`) on your machine and your friend's machine. Is that correct? If not, then explain exactly what you mean. – jww Aug 24 '19 at 05:48
  • 1
    Also see [Python path.join behavior is different when run in Mac vs Windows](https://stackoverflow.com/q/18138563/608639), [Cross-platform Desktop directory path?](https://stackoverflow.com/q/7403918/608639), [Platform-independent file paths?](https://stackoverflow.com/q/6036129/608639), [constructing absolute path with os.path.join()](https://stackoverflow.com/q/17429044/608639), [Unix paths that work for any platform in Python?](https://stackoverflow.com/q/1633643/608639), [Platform independent path concatenation using “/” , “\”?](https://stackoverflow.com/q/10918682/608639), etc. – jww Aug 24 '19 at 05:55
  • Thank you for the replies and the edits. That's basically what I am looking for. – JM9 Aug 24 '19 at 06:48
  • Possible duplicate of [How can I safely create a nested directory?](https://stackoverflow.com/q/273192/608639), [How can I create directories recursively?](https://stackoverflow.com/q/6004073/608639), [How to create directories and sub directories efficiently and elegantly in Python](https://stackoverflow.com/q/30837089/608639), [mkdir -p functionality in Python](https://stackoverflow.com/q/600268/608639), etc. – jww Aug 24 '19 at 07:26

1 Answers1

1

Your code can check the existence of the directory and create it if not found:

if not os.path.exists("/home/myname/directory"):
    os.makedirs("/home/myname/directory")
    # do something
Ahmed Arafa
  • 420
  • 3
  • 4