Python Win 32 error while trying to rename a file - python

I have a folder with several csv-files in it. I have to change the filename of every file with a string that I find in the file. So I tried the script below. It looks like it is working until I try to rename the file.
What did I try:
First I didn't have the file.close() line in the program, but did didn't fix the problem
I added a line print(file.closed) to see if the file was actually closed
I tried to get the os.rename out of the indented 'with' block. But I keep getting the same error
I tried to get the os.rename out of any block. But then I get a Winerror 123, where it sais that the filename , directoryname etc. is incorrect.
I also read the questions WindowsError 32 while trying to os.rename and Windows Error: 32 when trying to rename file in python.
I understood that maybe I had to close the file with f.close since this is the handler, but that didn't work as well.
The code that I tried:
for f in glob.glob("/path/*.csv"):
with open(f, "r") as file:
#read the lines in the csv-file
data = file.read()
#search the lines that have been read for a pattern and save that in "search"
search = re.findall("some_pattern", data)
#The result was a list. With this line I tried to change it into a string
file.close()
Listtostring = ''.join([str(elem) for elem in search])
#I only want to use a part of the match in the new file name
name = Listtostring.replace("part_of_string", "")
os.rename(f,f+name)
I hope somebody can give me some tips and explain what I am doing wrong. Pretty new to Python, so if you can give me some insight in my mistakes, than it's appreciated!

Thank you for your comments and time. It seemed that one of the files that was opened was still busy in some process and therefore the code didn’t work. I first closed all the applications that were running, but that didn’t work. After that I restarted the computer and the script worked fine!

Related

My function is not calling properly after I close a file?

I am in an intro class and I've been looking for an answer for hours but I can't find one. My assignment is to use a txt. file and the list in it as an address book and whenever I call my menu() function after closing the file it doesn't run right it just is blank, I've printed "H" in places throughout the program to find where the logic error is and I've singled it down to after I close the file on line 47, If anybody would be able to help me it would be greatly appreciated and I'm a noob so roast my code as much as you like.my code
How are you opening the file right now? You may be opening the file in a write mode that overwrites prior content, if so I would suggest using open in the following form:
with open("demofile.txt", "r") as file:
# Do things with file such as reading the lines
lines = file.readlines()
...
This way the file will be open in read-only mode
Your code while open the file may throw some error and thus ending the try statement. Try using with statement or raise the error on except to track where's the error.

Find lines which contain a specific word

First of all I have done a great research and tried many approaches to look for solution but maybe I am doing it wrong and was not able to find a solution.
My data:
https://knsim.com/test.txt
The problem is that I want to fill all the occurrence of 'Idea_Print' in a new file (not just the name 'Idea_Print' but the complete line of log.
I have tried many approaches but had not success.
My recent code:
file = open(filename, 'r')
for line in file:
if 'Idea_Print' in line:
print(line)
But this didn't work for me. I even tried using re but no success.
Thanks for help.
I tried running your code with my setup and it worked fine. Most likely, you are using the wrong filename in open().
In file = open(filename, 'r'), make sure that filename is the exact same name as your saved data, including extension. Ensure that the file you are trying to access is in the same folder as your python file. If it is not in the same folder, try including the full path to the file.
Also, at the end of your program make sure you call file.close() to allow other programs to access it correctly.
Another thing that could be causing problems is that your variable is called file. This is a built-in name in Python, so you probably don't want to overwrite it. Try changing it to something like data_file.
Edit: Looking at that file it appears that there is a space between every character. That means you will need to use 'E p i s o d e _ 2 0' instead of 'Episode_20'. However, it appears that even that does not appear in the file. Maybe you should double-check that it is the text that you are looking for.

The python command-line file handling doesn't work? am i working correctly?

I am a new python learner and now i have entered into file handling.
I tried solution for my problem but failed, so posting my question. before duplication please consider my question.
I tried to create a file, it worked.
writing in the file also worked.
But when i tried to read the text or values in the file, it returns empty.
I use command line terminal to work with python and running in Ubuntu OS.
The coding which I have tried is given below. The file is created in the desired location and the written text is also present.
f0=open("filehandling.txt","wb")
f0.write("my second attempt")
s=f0.read(10);
print s
I also tried with wb+, r+. But it just returns as empty
edit 1:
I have attached the coding below. I entered one by one in command line
fo = open("samp.txt", "wb")
fo.write( "Text is here\n");
fo.close()
fo = open("samp.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
fo.close()
First of all if you open with wb flag then the file will be only in writeable mode. If you want to both read and write then you need wb+ flag. If you don't want the file to be truncated each time then you need rb+.
Now files are streams with pointers pointing at a certain location inside the file. If you write
f0.write("my second attempt")
then the pointer points at the [pointer before writing] (in your case the begining of the file, i.e. 0) plus [length of written bytes] (in your case 17, which is the end of the file). In order to read whole file you have to move that pointer back to the begining and then read:
f0.seek(0)
data = f0.read()

Python2.7 file.obj.write(str) not writing to file

new python2.7 user here. I've searched for similar queries and I can't quite see what I'm doing wrong. I have a short script to read though all the files in a directory, and reading each one in turn, write them to a single master file.
My code is below; I can see two things going wrong at this time (although I get no error messages), 1 - that it only appears to open the first file in the list its supposed to be looping through (so my guess is I've an error using glob?), and 2 - although the print(str) statements display to the console nps, the output file never gets written too.
I've double checked that the file exists, it is empty and I'm passing the correct path & filename in when I call the function.
Any help is much appreciated.
#!/usr/bin/env python
import glob
import sys
filestoberecognised=sys.argv[1]
outputfile=sys.argv[2]
filecontents=glob.glob(filestoberecognised)
with open(outputfile,'w+') as f:
for i, row in enumerate(filecontents):
print(row) # this correctly prints to console
f.write(row+'\n') # this should write the filename of the filestoberecognised to the outputfile
with open(row,'r') as labfile:
for j, line in enumerate(labfile): # this should write words in label file
f.write('%s'%(line))
print('%s'%(line))
labfile.close() # ensures each file looped through is closed
f.write('\n.\n')
f.flush()
f.close()

Creating a new file in Python

I am a beginner, writing a python script in which I need it to create a file that I can write information to. However, I am having problems getting it to create a new, not previously existing file.
for example, I have:
file = open(coordinates.kml, 'w')
which it proceeds to tell me:
nameerror: name 'coordinates' is not defined.
Of course it isn't defined, I'm trying to make that file.
Everything I read on creating a new file says to take this route, but it simply will not allow me. What am I doing wrong?
I even tried to flat out define it...
file = coordinates.kml
file_open = open(file, 'w')
... and essentially got the same result.
You need to pass coordinates.kml as a string, so place them in quotes (single or double is fine).
file = open("coordinates.kml", "w")
In addition to the above answer,
If you want to create a file in the same path, then no problem or else you need to specify the path as well in the quotes.
But surely opening a file with read permission will throw an error as you are trying to access an nonexistent file.
To be future proof and independent of the platforms you can read and write files in binaries. For example if this is Python on Windows, there could be some alternations done to the end of line. Hence reading and writing in Binary mode should help, using switches "rb" and "wb"
file = open("coordinates.kml", "wb")
And also remember to close the file session, else can throw errors while re running the script.

Categories

Resources