Home > OS >  Unable to open the file in txt in python
Unable to open the file in txt in python

Time:10-13

I have difficulty importing this file so that I can use it any help would greatly be appreciated.

import os 
path = os.path.abspath(r'C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt')
cars=open(path)
print (cars)

for line in cars:
    values = line.split ()
    print(values[0], 'has an MPG of', values[2], 'with', values[5])
    
    # TODO: Split the line into a list of strings
     
    
    # TODO: Print the sentence
     

# Close the file
cars.close()

FileNotFoundError                         Traceback (most recent call last)
Input In [14], in <cell line: 3>()
      1 import os 
      2 path = os.path.abspath(r'C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt')
----> 3 cars=open(path)
      4 print (cars)
      6 for line in cars:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/kariwhite/Desktop/430 Python/week 4/C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt'

CodePudding user response:

When reading files on python I'd highly recommend using the os.path module. It helps combine paths depending on which OS you're using. Assuming you're sure that the file exists, try the following:

import os

pwd = os.path.join("c:/", "Users", "kariwhite","Desktop","430 Python", "week 4", "cars.txt")

with open(pwd, "r") as file:
    for line in file:
        values = line.split() 
        #...

I'd highly recommend reading files using the syntax highlighted here too. with open() as file: ... is the best practice for file handling.

CodePudding user response:

If you’re working in User/kariwhite/

Try

os.path.abspath(“Desktop/430 Python/week 4/cars.txt”)

You typically have to start the path from your current working directory if it’s moving forward from there and not in a sub directory.

CodePudding user response:

Please note that the os.path.abspath() takes a path or file name as a parameter representing a file system path and returns a normalized version of the pathname path.

If the file actually exists in the specified directory (Users/kariwhite/Desktop/430 Python/week 4/cars.txt) and your working directory is Users/kariwhite/Desktop/430 Python/week 4 the below should work:

import os 
path = os.path.abspath("cars.txt")
cars=open(path)
print (cars)

Also, if the file is in the current working directory you could use the relative path by opening the file directly:

import os
cars=open("cars.txt")
print (cars)
  • Related