0

I'm trying to write a code that takes a file name as an input. Finds this file on my computer and then changes the name of the file according to the text on the 2 first lines of the file.

import os
filename = input("Enter your file name: ")

def info(filename):
    with open(filename, 'r') as filehandle:
        current_line = 1
        for line in filehandle:
            if current_line <=2:
                yield(line)
            current_line += 1
    

info = list(info(filename))
print(info)
path = r'C:\Users\marku\Desktop\INF100'
date = str(info[1])
place = str(info[0])

finalname = date + '_' + place + '.txt'
old = os.path.join(path, filename)
new = os.path.join(path, finalname)

os.rename(old, new)

However, I get WinError 123 when trying to run this code.

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 
  'C:\\Users\\marku\\Desktop\\INF100\\qwerty.txt' -> 'C:\\Users\\marku\\Desktop\\INF100\\2019-06-01\n_Oslo\n.txt'
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Please post the full error traceback as part of your question. –  Oct 16 '20 at 17:12
  • Does this answer your question? [Python - os.rename() - OSError: \[WinError 123\]](https://stackoverflow.com/questions/21115580/python-os-rename-oserror-winerror-123) –  Oct 16 '20 at 17:13
  • Yeah, this is what I thought the issue was the fact there is a "\n" in the filename. I tried to change this after making each element of the list a string. but it seems as if it isn't part of the string it's part of the filename. I'm not sure how to remove this from the new filename. – Markus Hamre Oct 16 '20 at 17:25
  • Given the line `for line in filehandle:`, `line` would then include the trailing `'\n'` (linefeed character). You may want to do `yield(line.strip())` to remove the linefeed character. –  Oct 16 '20 at 17:32
  • Thank you Justin, absolute legend! Appreciate the help – Markus Hamre Oct 16 '20 at 17:40
  • You need to ensure a legal filename. It cannot include ASCII control characters 1-31, the path separators (``\`` and `/`), the file-stream delimiter (`:`), vertical bar (`|`), or the five wildcard characters (`*?"<>`). It also cannot end with a trailing dot (`.`) or space. It also cannot be a reserved device name (case insensitive): `NUL`, `CON`, `CONIN$`, `CONOUT$`, `AUX`, `PRN`, `COM1` - `COM9`, or `LPT1` - `LPT9`. This includes the base device name followed by zero or more spaces, a dot (`.`), and zero or more characters (e.g. `con.eggs` or `nul .spam`). – Eryk Sun Oct 16 '20 at 18:20

0 Answers0