I can't make a search-and-replace script for Python - python

I've been trying to do this, but I'm pretty new at Python, and can't figure out how to make it work.
I have this:
import fileinput
for line in fileinput.input(['tooltips.txt'], inplace=True, backup="bak.txt"):
line.replace("oldString1", "newString1")
line.replace("oldString2", "newString2")
But it just deletes everything from the txt.
What am I doing wrong?
I have tried with print(line.replace("oldString1", "newString1")
but it doesn't remove the existing words.
As I said, I'm pretty new at this.
Thanks!

line.replace() doesn't modify line it returns the modified string
import fileinput, sys
for line in fileinput.input(['tooltips.txt'], inplace=True, backup="bak.txt"):
sys.stdout.write(line.replace("oldString1", "newString1"))

One simple way to do this is with the open function and the os module:
import os
with open(tmp_file) as tmp:
with open(my_file) as f:
for line in f.readlines():
tmp.write(line.replace("oldString1", "newString1").replace("oldString2", "newString2") + "\n")
os.remove(my_file)
os.rename(tmp_file, my_file)

Related

TypeError when write a dictionary to csv file [duplicate]

I have a very simple python script that should scan a text file, which contains lines formatted as id='value' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:
import os,sys
from os import *
from sys import *
vals = {}
f = open(sys.argv[1], 'r')
for line in val_f:
t = line.split('=')
t[1].strip('\'')
vals.append(t[0], t[1])
print vals
f.close()
when i try to run it i get:
Traceback (most recent call last):
File "chval.py", line 9, in ?
f = open(sys.argv[1], 'r') TypeError: an integer is required
I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer?
anything after that line is untested. in short: why is it giving me the error and how do i fix it?
Because you did from os import *, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error.
Don't do import * from wherever without a good reason (and there aren't many).
Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do import os then call os.open(....). Whichever open you want to call, read the documentation about what arguments it requires.
Also of note is that starting with Python 2.6 the built-in function open() is now an alias for the io.open() function. It was even considered removing the built-in open() in Python 3 and requiring the usage of io.open, in order to avoid accidental namespace collisions resulting from things such as "from blah import *". In Python 2.6+ you can write (and can also consider this style to be good practice):
import io
filehandle = io.open(sys.argv[1], 'r')
Providing these parameters resolved my issue:
with open('tomorrow.txt', mode='w', encoding='UTF-8', errors='strict', buffering=1) as file:
file.write(result)
From http://www.tutorialspoint.com/python/os_open.htm you could also keep your import and use
file = os.open( "foo.txt", mode )
and the mode could be :
os.O_RDONLY: open for reading only
os.O_WRONLY: open for writing only
os.O_RDWR : open for reading and writing
os.O_NONBLOCK: do not block on open
os.O_APPEND: append on each write
os.O_CREAT: create file if it does not exist
os.O_TRUNC: truncate size to 0
os.O_EXCL: error if create and file exists
os.O_SHLOCK: atomically obtain a shared lock
os.O_EXLOCK: atomically obtain an exclusive lock
os.O_DIRECT: eliminate or reduce cache effects
os.O_FSYNC : synchronous writes
os.O_NOFOLLOW: do not follow symlinks
that's because you should do:
open(sys.argv[2], "w", encoding="utf-8")
or
open(sys.argv[2], "w")
you have from os import * I also got the same error, remove that line and change it to import os and behind the os lib functions, add os.[function]

Change all text in file to lowercase

from itertools import chain
from glob import glob
file = open('FortInventory.txt','w')
lines = [line.lower() for line in lines]
with open('FortInventory.txt', 'w') as out:
out.writelines(sorted(lines))
I am trying to convert all text in a txt file to lowercase how would i go about doing this, here is the code i have so far and i looked at some questions on stack overflow but i couldnt quite figure it out, if anyone could link me to the right article or tell me what is wrong with my code i would greatly appreciate it.
Two problems:
Open the file with 'r' for read.
Change lines to file in your list comprehension.
Here's the fixed code:
from itertools import chain
from glob import glob
file = open('FortInventory.txt', 'r')
lines = [line.lower() for line in file]
with open('FortInventory.txt', 'w') as out:
out.writelines(sorted(lines))

How to write the output of a os.walk to file

I have a simple 2 line code and i need to write the output to a file. The code is as follows:
import os,sys
print next(os.walk('/var/lib/tomcat7/webapps/'))[1]
How to do it ?
Use open() method to open file, write to write to it and close to close it as in lines below:
import os,sys
with open('myfile','w') as f:
# note that i've applied str before writing next(...)[1] to file
f.write(str(next(os.walk('/var/lib/tomcat7/webapps/'))[1]))
See Reading and Writing Files tutorial for more information of how to deal with files in python and What is the python "with" statement designed for? SO question to get better understanding of with statement.
Good Luck !
In Python 3 you can use the file parameter to the print() function:
import os
with open('outfile', 'w') as outfile:
print(next(os.walk('/var/lib/tomcat7/webapps/'))[1], file=outfile)
which saves you the bother of converting to a string, and also adds a new line after the output.
The same works in Python 2 if you add this import at the top of your python file:
from __future__ import print_function
Also in Python 2 you can use the "print chevron" syntax (that is if you do not add the above import):
with open('outfile', 'w') as outfile:
print >>outfile, next(os.walk('/var/lib/tomcat7/webapps/'))[1]
Using print >> also adds a new line at the end of each print.
In either Python version you can use file.write():
with open('outfile', 'w') as outfile:
outfile.write('{!r}\n'.format(next(os.walk('/var/lib/tomcat7/webapps/'))[1]))
which requires you to explicitly convert to a string and explicitly add a new line.
I think the first option is best.

importing external ".txt" file in python

I am trying to import a text with a list about 10 words.
import words.txt
That doesn't work...
Anyway, Can I import the file without this showing up?
Traceback (most recent call last):
File "D:/python/p1.py", line 9, in <module>
import words.txt
ImportError: No module named 'words'
Any sort of help is appreciated.
You can import modules but not text files. If you want to print the content do the following:
Open a text file for reading:
f = open('words.txt', 'r')
Store content in a variable:
content = f.read()
Print content of this file:
print(content)
After you're done close a file:
f.close()
As you can't import a .txt file, I would suggest to read words this way.
list_ = open("world.txt").read().split()
The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:
text = open("words.txt", "rb").read()
This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python
with open('words.txt') as fp:
contents = fp.read()
for entry in contents:
# do something with entry
numpy's genfromtxt or loadtxt is what I use:
import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')
This got me headed in the right direction and solved my problem.
Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.

Unable to extract information from Linux shell command using python

I am creating a Python script to collect data on underlying hardware from cat /proc/cpuinfo
I am trying to extract information i need. But I am having a problem. Here is the script
import os
p=os.popen ("cat /proc/cpuinfo")
string=[]
i=0
for line in p.readlines():
string.append(line.split(":"))
if(string[i][0]=='model name'):
fout = open("information.txt", "w")
fout.write("processor:")
fout.write(string[i][1])
fout.close()
i+=1
My program does not enter if loop at all why? Thanks in advance for help
There is no point to use cat at all here. Refactor it like this:
with open("/proc/cpuinfo") as f:
for line in f:
# potato potato ...
it probably does enter the loop but there might be a whitespace around "model name". You could call .strip() to remove it.
You can open /proc/cpuinfo as a file:
with open("/proc/cpuinfo") as file:
for line in file:
key, sep, value = line.partition(":")
if sep and key.strip() == "model name":
with open("information.txt", "w") as outfile:
outfile.write("processor:" + value.strip())
break
Hard to say what exactly is wrong. I could not figure that out at a glance, though on my Ubuntu 12.10 it also fails in the same way. Anyway, use the subprocess module since popen is deprecated.
subprocess.check_output(['cat', '/proc/cpuinfo']) returns a string quite successfully, at least on my system. And subprocess.check_output(['cat', '/proc/cpuinfo']).split('\n') will give you a list you may iterate through.
Also note that string[i][0]=='model name' won't work. There are tabs after splitting that line by ':'. Do not forget to call strip(): string[i][0].strip()=='model name'
Then, on Python 2.6+ (or even 2.5+, though 2.5 requires from __future__ import with_statement) it's almost always a good practice to use with for dealing with a file you need to open:
with open("information.txt", "w") as fout:
fout.write("processor:")
fout.write(string[i][1])
And finally, those saying you may just open a file and read it, are quite right. That is the best solution:
with open('/proc/cpuinfo') as f:
#Here you may read the file directly.
You could try doing it as :
for line in p.readlines():
line=line.split(":")
if(line[0]=='model name\t') :
#Do work
If you dont need the complete list string.

Categories

Resources