Newline character appearing in txt file of paths


3 posts
by FeersumEndjinn » Mon Feb 04, 2013 3:06 pm
Hi all,

I'm loading a text file which contains a path to a file on each line. However, I'm having issues with the newline character.

This is how I'm reading in the data:
Code: Select all
def parse_remote_paths(remote_config_path):

   remote_paths_list = []
   _remote_paths_list_file = open(os.path.normpath(remote_config_path), 'r')
   _remote_paths_list_lines = _remote_paths_list_file.readlines()
   
   for _line in _remote_paths_list_lines:
      _norm_line = os.path.normpath(_line)
      remote_paths_list.append(_norm_line)
  return remote_paths_list

However, the content of this list ends up as:

Code: Select all
['\\\\dworkin\\FeersumEndjinn\\difftest\\one.config\n', '\\\\dworkin\\FeersumEndjinn\\difftest\\eventlogger.config\n',
'\\\\dworkin\\FeersumEndjinn\\difftest\\spec01.config']


Ignore the multiple backslashes as this is pulling files from a Windows share, and os.path.normpath fixes the slashes for me (tried and tested!). However it does appear that normpath is ignoring the \n and probably assuming it's part of the path rather than a newline command.

What I have having problems with, is the end of all but the last last has a \n newline character added?

What is the best way to accomodate that and get rid of it? Should I iterate through each row in the file and use string slicing in a conditional replace statement?

i.e.
Code: Select all
# pseudo code!
for line in file:
    if line[-2:] == "\n":
        line = line[:-2]


Or is there a proper way to drop the newline character that I'm totally missing, i.e. by reading the file in a different way?

Kind Regards,
FeersumEndjinn
Morrolan / FeersumEndjinn

"And the lord God said unto John, 'Come forth and receive eternal life', but John came fifth and won a toaster."
User avatar
Posts: 141
Joined: Mon Nov 21, 2011 4:02 pm
by bgreat » Mon Feb 04, 2013 3:20 pm
Try:
Code: Select all
      remote_paths_list.append(_norm_line.strip())


From built-in documentation:
Code: Select all
Help on built-in function strip:

strip(...)
    S.strip([chars]) -> string or unicode

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping


Enjoy!
Bill
User avatar
Posts: 235
Joined: Mon Jan 23, 2012 2:09 pm
by FeersumEndjinn » Mon Feb 04, 2013 3:28 pm
You sir, are a genius :)
Morrolan / FeersumEndjinn

"And the lord God said unto John, 'Come forth and receive eternal life', but John came fifth and won a toaster."
User avatar
Posts: 141
Joined: Mon Nov 21, 2011 4:02 pm