0

I am trying to open a file "test_msm8974.sh" from the root directory using the following code,even though the file is present I keep getting the error beow,is there a better way to implement this or suggestions on why the script is not finding it?

try:
    with open("test_" + target + ".sh") as f: pass
    copy("test_" + target + ".sh", BUILD_ROOT_DIR)
except IOError as e:
    print "test_" + target + ".sh" + " file missing"
    raise

I keep getting the following error even though the file is present

Traceback (most recent call last):
  File "g2g_integration.py", line 612, in <module>
    main()
  File "g2g_integration.py", line 430, in main
    with open("test_" + target + ".sh") as f: pass
IOError: [Errno 2] No such file or directory: 'test_msm8974.sh'
user1934146
  • 2,905
  • 10
  • 25
  • 25

1 Answers1

0

What's the output of os.getcwd()? Is it the same directory as your target file?

Overall, I would prefer using os.path.exists and os.path.isfile (etc) rather than trying to open the file. Also, you have a lot of duplication in your code with "test_" + target + ".sh". You should save that in a variable.

forivall
  • 9,504
  • 2
  • 33
  • 58
  • `os.path.exists` isn't often very useful. It doesn't tell you the file exists, as it could have been deleted after you checked. It doesn't tell you the file doesn't exist, as it could have been created immediately after you checked. All it tells you is whether it existed at some point. To handle the case where the file stopped existing before you try to do something with it you're probably going to use a `try/except` pair anyhow, and so 90% of the time you're better off simply doing that.. – DSM Jan 16 '13 at 20:24
  • 1
    Presumably `copy()` will raise an exception if the file doesn't exist, so I think the `open()` line can simply be deleted. –  Jan 16 '13 at 20:32
  • @forivall - os.getcwd gives the correct directory where the file test_msm8974.sh is present.. – user1934146 Jan 16 '13 at 20:35
  • @DSM The chance that that race condition is going to occur is so low, that it's a matter of preference to do a try/except vs a test. – forivall Jan 16 '13 at 20:39
  • @BrianMarshall I'm guessing that it's shutil.copy, which tries to open the file in 'rb' mode; so you're right. – forivall Jan 16 '13 at 20:40