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.
Related
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!
I am a newbie python developer and I have a question.
I have a python script check if updates are available on an external webpage but I got stuck while trying to get it to override old file with new one. What the code does below is get new.py and open it as a txt file. It then searches for __VERSION__. My code for searching for new version is below. How would I replace current.py with new.py?
__VERSION__ = '1.0'
#Get new version
new_version = ''
with open('new.py') as newfile:
for line in newfile:
line = line.strip()
if '__VERSION__' in line:
_, new_version = line.split('=', maxsplit=1)
new_version = new_version.strip()
break
Thanks #user:6530979
Can anyone help me understand what to do after this?
EDIT: The goal is for current.py to override its self with new.py’s code
Any help will be appreciated!!
Overall, these solutions are hacky at best-- no guarantees.
You SHOULD look into package management/version control, because the systems already developed to do this are likely to be much more reliable.
BUT, you might be able to use os.rename. I'm not sure if this is a good solution, or how safe it is, but it worked in my quick trial.
''' current.py (V1) '''
import os
os.rename("current.py", "old.py")
os.rename("new.py", "current.py")
In this case, current.py (V1) is the file run by the user. After execution, you are left with old.py and current.py (V2).
Two things to note:
You won't have line-by-line control via this method.
You might want to make this program call another (like V1 calling V2 and then exiting), using strategies such as these.
# what you want to replace '__VERSION__' with
replace = 'what ever you want'
new_lines = []
with open('new.py',"r") as newfile:
lines = newfile.readlines()
for line in lines:
new_lines.append(line.replace("__VERSION__", replace))
with open('new.py',"w") as newfile2:
full_file_text = "".join(new_lines)
newfile2.write(full_file_text)
is this what you wanted? to replace some text in a specific line?
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.
From what I've researched, csv.writeRow should take in a list, and then write it to the given csv file. Here's what I tried:
from csv import writer
with open('Test.csv', 'wb') as file:
csvFile, count = writer(file), 0
titles = ["Hello", "World", "My", "Name", "Is", "Simon"]
csvFile.writerow(titles)
I'm just trying to write it so that each word is in a different column.
When I open the file that it creates, however, I get the following message:
After pressing to continue anyways, I get a message saying that the file is either corrupted, or is a SYLK file. I can then open the file, but only after going through two error messages everytime I open the file.
Why is this?
Thanks!
It's a documented issue that Excel will assume a csv file is SYLK if the first two characters are 'ID'.
Venturing into the realm of opinion - it shouldn't, but Excel thinks it knows better than the extension. To be fair, people expect it to be able to figure out cases where the extension really is wrong, but in a case like this assuming the extension is wrong, and then further assuming the file is corrupt when it doesn't appear corrupt if interpreted according to the extension is just mind-boggling.
#John Y points out:
One thing to watch out for: The "workaround" given by the Microsoft issue linked to by #PeterDeGlopper is to (manually) prepend an apostrophe into the file. (This is also advice commonly found on the Web, including StackOverflow, to try to force CSV digits to be treated as strings rather than numbers.) This is not what I'd call good advice, as that injects a literal apostrophe into your data.
#DSM suggests using quoting=csv.QUOTE_NONNUMERIC on the writer. Excel is not confused by a file beginning with "ID" rather than ID, so if the other tools that are going to work with the CSV accept that quoting level this is probably the best solution other than just ignoring Excel's confusion.
The Problem - Update:
I could get the script to print out but had a hard time trying to figure out a way to put the stdout into a file instead of on a screen. the below script worked on printing results to the screen. I posted the solution right after this code, scroll to the [ solution ] at the bottom.
First post:
I'm using Python 2.7.3. I am trying to extract the last words of a text file after the colon (:) and write them into another txt file. So far I am able to print the results on the screen and it works perfectly, but when I try to write the results to a new file it gives me str has no attribute write/writeline. Here it the code snippet:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
def ripple(x):
with open(x) as file:
for line in file:
for word in line.split():
if ':' in word:
try:
print word.split(':')[-1]
except (IndexError):
pass
ripple(x)
The code above works perfectly when printing to the screen. However I have spent hours reading Python's documentation and can't seem to find a way to have the results written to a file. I know how to open a file and write to it with writeline, readline, etc, but it doesn't seem to work with strings.
Any suggestions on how to achieve this?
PS: I didn't add the code that caused the write error, because I figured this would be easier to look at.
End of First Post
The Solution - Update:
Managed to get python to extract and save it into another file with the code below.
The Code:
inputFile = open ('c:/folder/Thefile.txt', 'r')
outputFile = open ('c:/folder/ExtractedFile.txt', 'w')
tempStore = outputFile
for line in inputFile:
for word in line.split():
if ':' in word:
splitting = word.split(':')[-1]
tempStore.writelines(splitting +'\n')
print splitting
inputFile.close()
outputFile.close()
Update:
checkout droogans code over mine, it was more efficient.
Try this:
with open('workfile', 'w') as f:
f.write(word.split(':')[-1] + '\n')
If you really want to use the print method, you can:
from __future__ import print_function
print("hi there", file=f)
according to Correct way to write line to file in Python. You should add the __future__ import if you are using python 2, if you are using python 3 it's already there.
I think your question is good, and when you're done, you should head over to code review and get your code looked at for other things I've noticed:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
First off, thanks for putting example file contents at the top of your question.
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
I don't think this part is neccessary. You can just create a better parameter for ripple than x. I think file_loc is a pretty standard one.
def ripple(x):
with open(x) as file:
With open, you are able to mark the operation happening to the file. I also like to name my file object according to its job. In other words, with open(file_loc, 'r') as r: reminds me that r.foo is going to be my file that is being read from.
for line in file:
for word in line.split():
if ':' in word:
First off, your for word in line.split() statement does nothing but put the "Hello:there:buddy" string into a list: ["Hello:there:buddy"]. A better idea would be to pass split an argument, which does more or less what you're trying to do here. For example, "Hello:there:buddy".split(":") would output ['Hello', 'there', 'buddy'], making your search for colons an accomplished task.
try:
print word.split(':')[-1]
except (IndexError):
pass
Another advantage is that you won't need to check for an IndexError, since you'll have, at least, an empty string, which when split, comes back as an empty string. In other words, it'll write nothing for that line.
ripple(x)
For ripple(x), you would instead call ripple('/home/user/sometext.txt').
So, try looking over this, and explore code review. There's a guy named Winston who does really awesome work with Python and self-described newbies. I always pick up new tricks from that guy.
Here is my take on it, re-written out:
import os #for renaming the output file
def ripple(file_loc='/typical/location/while/developing.txt'):
outfile = "output.".join(os.path.basename(file_loc).split('.'))
with open(outfile, 'w') as w:
lines = open(file_loc, 'r').readlines() #everything is one giant list
w.write('\n'.join([line.split(':')[-1] for line in lines]))
ripple()
Try breaking this down, line by line, and changing things around. It's pretty condensed, but once you pick up comprehensions and using lists, it'll be more natural to read code this way.
You are trying to call .write() on a string object.
You either got your arguments mixed up (you'll need to call fileobject.write(yourdata), not yourdata.write(fileobject)) or you accidentally re-used the same variable for both your open destination file object and storing a string.