0
a01:01-24-2011:s1 
a03:01-24-2011:s2 
a02:01-24-2011:s2 
a03:02-02-2011:s2 
a03:03-02-2011:s1 
a02:04-19-2011:s2 
a01:05-14-2011:s2 
a02:06-11-2011:s2 
a03:07-12-2011:s1 
a01:08-19-2011:s1 
a03:09-19-2011:s1 
a03:10-19-2011:s2 
a03:11-19-2011:s1 
a03:12-19-2011:s2 

this is saved in animallog1.txt. How would I import this file so that it can be used to write code, or answer questions using the above data. I have tried:

 open('C:/animallog1.txt', 'r') 

but it does not work and states FileNotFoundError: [Errno 2] No such file or directory: 'C:/animallog1.txt' Could someone please help me fix this

1
  • 1
    @wwii You need raw string for the backslash '\' (or to escape it with another backslash '\\') but not forward slash '/'. Commented Nov 24, 2013 at 5:35

3 Answers 3

1
open('C:\\animallog1.txt', 'r') 
Sign up to request clarification or add additional context in comments.

Comments

0
  1. Does file animallog1.txt exists?

  2. On Windows you should be care for the backsplash.

    file = open('c:\\path\\to\\file', 'r')
    

    or

    file = open(r'c:\path\to\file', 'r')    
    
  3. Check your workspace, u can use os.chdir() to change your directory to c:\?

2 Comments

builtins.ImportError: No module named 'animallog1'
@user2994135 How could it be? this means u import a non-existent module, and your operation is open a file. I think u used import animallog1.
0

First, if you're using Windows, you have to use backslashes. There are a couple ways to do that: one is with double backslashes as others have pointed out, another is using the various constants and functions in the os and os.path libraries:

import os
filename = "C:" + os.sep + "animallog1.txt"

Second, the "proper" way to do this is with a with statement:

with open(filename) as f: #'r' is default
    for line in f:
        a, date, s = line.split(":")
        # ...

What the with statement does is guarantee that the file gets closed on leaving the with block. Otherwise the file doesn't get closed until the Python garbage collector gets around to it.

2 Comments

the file is saved is Computer-Windows(C:)-User-#my name-documents if that helps in anyway
Are you running the Python script in the same place as the file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.