-3

I want to read a file that is in a different path from my python file. This is what i tried to do and I finish by getting syntax errors every time.

fname = input("Enter file name: ")
fh = open("C:\Users\Computer\Desktop\Assignment 7.1\%s" %fname)

This is what I tried to do.

MEDX
  • 89
  • 8
  • here, this explain very well how to do it with examples https://www.pythontutorial.net/python-basics/python-read-text-file/ –  Mar 02 '22 at 16:09
  • You're using the wrong slashes. Just replace each `"\"` with `"\\"`. – Random Davis Mar 02 '22 at 16:14
  • It is better to use forward slashes for a [Windows path in Python](https://stackoverflow.com/questions/2953834/) anyway. – Karl Knechtel Aug 07 '22 at 05:24

3 Answers3

2

You are using the wrong slashes (i.e \ instead of \\). Also, check if the path you are trying to reach exists (Computer being a subfolder of the Users folder doesn't sound right).

In addition, if you are going with string concatenation, I'd recommend using python's f-strings, like so:

fh = open(f"C:\\Users\\Computer\\Desktop\\Assignment 7.1\\{fname})

However, to avoid issues as you just encountered, I would just use os.path.join:

import os
path = os.path.join("C:", "Users", "Computer", "Desktop", "Assignment 7.1", fname)
fh = open(path)

I'd also change the variable names to be separated by underscores.

Secondly, it is preferable to use a context manager (i.e the with keyword). The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point:

import os
file_name = input("Enter file name: ")
path = os.path.join("C:", "Users", "Computer", "Desktop", "Assignment 7.1", fname)
with open(path) as file_handler:
    file_content = file_handler.read() # to get the files content

You can also read more about how to handle reading and writing from files in python here.

1

The '' character is Python strings is used to "escape", to type special characters like newlines or tabs. So, if you want to type backslash, you have to type it as \\, giving C:\\Users\\Computer\\Desktop\\Assignment 7.1\\.

In general, I'd advise using the pathlib module to prevent these headaches. You can then use the forward slash, which does not have to be escaped.

from pathlib import Path

root_path = Path("C:") / "Users" / "Computer" / "Desktop" / "Assignment 7.1"
fname = input("Enter file name: ")
fh = open(root_path / fname)
eccentricOrange
  • 876
  • 5
  • 18
0

To open the file you should use built-in open() function The open() function returns a file object and you use a read() method for reading the content of the file:

    fh = open("C:\\Users\Computer\Desktop\Assignment 7.1", "r")
    print(fh.read()) 
Farshad Javid
  • 528
  • 5
  • 10
  • 1
    The question already uses `open`... You don't actually explain what is the problem (and didn't really fix it...) – Tomerikoo Mar 02 '22 at 16:30