Python 3.2: IOError: [Errno 22] Invalid argument: '/home/pi/data/temp/file1\n.txt'

I am new to python programming. I have a counter.txt file from which I read the counter value. Using this counter value, I have to create new files in another folder, for example '/home/pi/data/temp/file%s.txt'%line. for example: file1.txt, file2.txt, etc.

I wrote the code for this and for some reason I ran into the error below:

IOError: [Errno 22] Invalid argument: '/home/pi/data/temp/file1\n.txt'

      

My python code looks like this:

while True:

    counter_file = open("counter.txt", 'r+')
    line = counter_file.readline()
    print(line)
    counter_file.close()
    file_read = open(r'/home/pi/data/temp/file%s.txt'%line, 'w')
    #data_line = line_read.decode("utf-8")
    #file_read.write("%s"%data_line)
    file_read.close()
    counter_file = open("counter.txt", 'w')
    line = int(line) + 1
    counter_file.write("%s"%line)
    counter_file.truncate()
    counter_file.close()

      

While I am doing this I get this traceback:

 File "compute1.py", line 24, in <module>
    file_read = open(r'/home/pi/data/temp/file%s.txt'%line, 'w')
IOError: [Errno 22] Invalid argument: '/home/pi/data/temp/file1\n.txt'

      

Please help me in this regard. Thank you!

+3


source to share


2 answers


You need to remove the trailing newline from the variable line

. This can be done by simply clicking .strip()

on it. You can see the file path comes out as

/home/pi/data/temp/file1\n.txt

      

when you probably expect it to be



/home/pi/data/temp/file1.txt

      

This is because your file counter.txt

uses \n

as a newline character, so every line ends with it as well. When you use readline

it gets the full line including the newline, so you need to split it up. Try replacing this line with

line = counter_file.readline().strip()

      

+5


source


The process cannot write to a file in this directory. Either make it so that the process can, or write somewhere else.



0


source







All Articles