How to open a txt file that has a space in its python name?

Asked

Viewed 303 times

2

I’m learning to code in python and I’m having trouble opening a specific file. In case I can open text documents normally, but when there is space in the file name it does not locate the file. Thanks in advance for your help.

Ex diretorio: C: Desktop users File folder list Telefonica.txt

I’m using the code

import pandas as pd
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt

basedf = pd.read_csv('C:\Users\Desktop\Pasta do arquivo\lista telefonica.txt', delimiter="\t", dtype=str)

Report received by the tool

FileNotFoundError: [Errno 2] File C:\Users\Pasta do arquivo lista telefonica.txt does not exist: 'C:\\Users\\Pasta do arquivo\xlista telefonica.txt  

Thank you.

  • 1

    Note that in "report", the file name not found is "xlista Telefonica"?

  • I noticed yes, na realized the real name of the file starts with 0201 FILE and actually it replaced the zero with x

1 answer

2

The problem is not the spaces - the problem is the backslashes \ which are escape characters. Place an "r" prefix in the file name string r'c:\Users... or double each bar - as Python prints - to ensure that none is expanded to a special character. In case " 0201" is replaced by the special character with octal code "0201" which is printed as " x81" .

Another way to use is to always use bars forward "/" instead of \ to separate directories - which is the character used in all current operating systems - Python accepts this form in Windows as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.