1

I have several .txt file with similar name, such as data_00, data_01, ..., data_99. I tried to use np.loadtxt in a for loop to read it. Now, I can use r-string to read the values in the text file manually numerical = np.loadtxt(r'file_path\data_0.txt', delimiter=' '), it is working but I am thinking to loop through the files.

So when I tried to use f-string, but it is giving me error "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape"

number = np.arange(100)

for i in number:
    numerical = np.loadtxt(f'file_path\data_{i}.txt', delimiter=' ')

I also tried to use glob to import the value, (code shown below), not it is not giving me the correct values in same order.

file_path = 'file_path' 
file_pattern = "*.txt"

files_list = glob(os.path.join(file_path,file_pattern))

for f in files_list:
    print(f'----- Loading {f} -----')
    numerical = np.loadtxt(f, delimiter=' ', unpack=True)
AboAmmar
  • 5,439
  • 2
  • 13
  • 24

1 Answers1

1

r'file_path\data_0.txt' is a raw (or r-) string. That means that \ is treated as a literal backslash. Without the r prefix, it would have a special meaning as the escape character for strings.

f'file_path\data_{i}.txt' is an f-string. That means that {i} gets special treatment, but \ does not. The escape sequence \U (presumably in your actual path) must be followed by 8 hexadecimal digits that make up the code for a Unicode code point. Clearly this is not what you are looking for.

There are a few solutions available to you:

  1. Escape the \:

    f'file_path\\data_{i}.txt'
    

    This places a single backslash in your string

  2. Make the string both f- and raw:

    fr'file_path\data_{i}.txt'
    
  3. Stay away from backslashes entirely. Python understands forward slash as the path separator:

    f'file_path/data_{i}.txt'
    
  4. Have a function, like os.path.join add the path separator for you:

    os.path.join('file_path', f'data_{i}.txt')
    
  5. Use an r-string, with the format method instead of the newer f-string functionality:

    r'file_path\data_{}.txt'.format(i)
    
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264