I am trying to copy multiple files located in different directories into one single directory. For that I created a text file with the different file paths.
This is my code:
parent_dir = ‘//HFXDATA4/Data3/221111.00 HRM Creation of Flood Hazard Maps Heavy/40 Design/01 CIVIL’
directory = “inp_temp”
with open(‘E:\Model_File_Path.txt’,‘r’) as fp:
for line in fp:
I get the following error (note the added \n after the file extension). Is the added n what is causing the issue?
OSError : [Errno 22] Invalid argument: ‘//Hfxdata4/Data3/221111.00 HRM Creation of Flood Hazard Maps Heavy/40 Design/01 CIVIL/02 Modelling/SWMM/02 Modelling/00 Model Construction/shift_tests/MUSQ_ 1EK_5_6.inp\n’
When you iterate over a file, the lines include the trailing newline
"\n" at the end. You need to remove it. Easiest way to do that is:
with open('E:\Model_File_Path.txt','r') as fp:
for line in fp:
line = line.strip()
Technically the call to
strip() will remove any leading or trailing whitespace, not just a trailing newline, but that’s probably what you want.
Yes, the newline character, which is represented in a string literal using the escape
"\n", is not allowed in a filename on Windows. As demonstrated above, call the string’s
rstrip() method to remove the newline character.
Windows filesystems disallow the following characters in filenames:
- path separators – backslash (
\) and slash (
- the file stream separator – colon (
- wildcard characters – asterisk (
*), question mark (
?), less than (
DOS_STAR), greater than (
DOS_QM), and double quote (
DOS_DOT). For example, see the kernel’s filesystem runtime library function
- the pipe operator used by command-line shells – vertical bar (
- ASCII control characters (ordinals 0-31)
The newline character is an ASCII control character, i.e.
ord('\n') == 10.
Thank you so much! it worked! I am very new at this.
Thank you Eryk. I’ll keep these tips in mind