Python seemingly not reading from text file - python

files = []
with open("[...].log", "a+") as posshell:
for line in files:
print(line)
posshell_files.append(line)
I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.

You are passing the incorrect second argument to the open call to read the file in this way:
posshell_files = []
with open("posshell.log", "r") as posshell:
for line in posshell:
print(line)
posshell_files.append(line)
According to the Python docs for open, 'r' if the default flag for reading while 'a+' is for reading and writing but you will have to do so in a different manner:
with open("posshell.log","a+") as f:
f.seek(0)
print(f.read())

Try this
with open('posshell.log') as p:
content = p.readlines()
content = [x.strip() for x in content]

Related

Bulk autoreplacing string in the KML file

I have a set of placemarks, which include quite a wide description included in its balloon within the property. Next each single description (former column header) is bounded in . Because of the shapefile naming restriction to 10 characters only.
https://gis.stackexchange.com/questions/15784/bypassing-10-character-limit-of-field-name-in-shapefiles
I have to retype most of these names manually.
Obviously, I use Notepad++, where I can swiftly press Ctrl+F and toggle Replace mode, as you can see below.
The green bounded strings were already replaced, the red ones still remain.
Basically, if I press "Replace All" then it works fine and quickly. Unfortunately, I have to go one by one. As you can see I have around 20 separate strings to "Replace all". Is there a possibility to do it quicker? Because all the .kml files are similar to each other, this is going to be the same everywhere. I need some tool, which will be able to do auto-replace for these headers cut by 10 characters limit. I think, that maybe Python tools might be helpful.
https://pythonhosted.org/pykml/
But in the tool above there is no information about bulk KML editing.
How can I set something like the "Replace All" tool for all my strings preferably if possible?
UPDATE:
I tried the code below:
files = []
with open("YesNF016.kml") as f:
for line in f.readlines():
if line[-1] == '\n':
files.append(line[:-1])
else:
files.append(line)
old_expression = 'ab'
new_expression = 'it worked'
for file in files:
new_file = ""
with open(file) as f:
for line in f.readlines():
new_file += line.replace(old_expression, new_expression)
with open(file, 'w') as f:
f.write(new_file)
The debugger shows:
[Errno 22] Invalid argument: ''
File "\test.py", line 13, in
with open(file) as f:
whereas line 13 is:
with open(file) as f:
The solutions here:
https://www.reddit.com/r/learnpython/comments/b9cljd/oserror_while_using_elementtree_to_parse_simple/
and
OSError: [Errno 22] Invalid argument Getting invalid argument while parsing xml in python
weren't helpful enough for me.
So you want to replace all occurence of X to Y in bunch of files ?
Pretty easy.
Just create a file_list.txt containing the list of files to edit.
python code:
files = []
with open("file_list.txt") as f:
for line in f.readlines():
if line[-1] == '\n':
files.append(line[:-1])
else:
files.append(line)
old_expression = 'ab'
new_expression = 'it worked'
for file in files:
new_file = ""
with open(file) as f:
for line in f.readlines():
new_file += line.replace(old_expression, new_expression)
with open(file, 'w') as f:
f.write(new_file)

How can I tell python to edit another python file?

Right now, I have file.py and it prints the word "Hello" into text.txt.
f = open("text.txt")
f.write("Hello")
f.close()
I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:
f = open("list.py")
f.write("a = 1")
f.close
When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?
If you want to append a new line to the end of a file
with open("file.py", "a") as f:
f.write("\na = 1")
If you want to write a line to the beginning of a file try creating a new one
with open("file.py") as f:
lines = f.readlines()
with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))
with open("list.py","a") as f:
f.write("a=1")
This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.
Example:
with open("list.py","a") as f:
f.write("a=1")
f.write("\nprint(a+1)")
list.py
a=1
print(a+1)
Output from list.py:
>>>
2
>>>
As you see, there is a variable in list.py called a equal to 1.
I would recommend you specify opening mode, when you are opening a file for reading, writing, etc. For example:
for reading:
with open('afile.txt', 'r') as f: # 'r' is a reading mode
text = f.read()
for writing:
with open('afile.txt', 'w') as f: # 'w' is a writing mode
f.write("Some text")
If you are opening a file with 'w' (writing) mode, old file content will be removed. To avoid that appending mode exists:
with open('afile.txt', 'a') as f: # 'a' as an appending mode
f.write("additional text")
For more information, please, read documentation.

Confusing Error when Reading from a File in Python

I'm having a problem opening the names.txt file. I have checked that I am in the correct directory. Below is my code:
import os
print(os.getcwd())
def alpha_sort():
infile = open('names', 'r')
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
infile.close()
return 0
alpha_sort()
And the error I got:
FileNotFoundError: [Errno 2] No such file or directory: 'names'
Any ideas on what I'm doing wrong?
You mention in your question body that the file is "names.txt", however your code shows you trying to open a file called "names" (without the ".txt" extension). (Extensions are part of filenames.)
Try this instead:
infile = open('names.txt', 'r')
As a side note, make sure that when you open files you use universal mode, as windows and mac/unix have different representations of carriage returns (/r/n vs /n etc.). Universal mode gets python to handle this, so it's generally a good idea to use it whenever you need to read a file. (EDIT - should read: a text file, thanks cameron)
So the code would just look like this
infile = open( 'names.txt', 'rU' ) #capital U indicated to open the file in universal mode
This doesn't solve that issue, but you might consider using with when opening files:
with open('names', 'r') as infile:
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
return 0
This closes the file for you and handles exceptions as well.

Python- need to append characters to the beginning and end of each line in text file

I should preface that I am a complete Python Newbie.
Im trying to create a script that will loop through a directory and its subdirectories looking for text files. When it encounters a text file it will parse the file and convert it to NITF XML and upload to an FTP directory.
At this point I am still working on reading the text file into variables so that they can be inserted into the XML document in the right places. An example to the text file is as follows.
Headline
Subhead
By A person
Paragraph text.
And here is the code I have so far:
with open("path/to/textFile.txt") as f:
#content = f.readlines()
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
pth = os.getcwd()
print head,sub,auth,data,pth
My question is: how do I iterate through the body of the text file(data) and wrap each line in HTML P tags? For example;
<P>line of text in file </P> <P>Next line in text file</p>.
Something like
output_format = '<p>{}</p>\n'.format
with open('input') as fin, open('output', 'w') as fout:
fout.writelines( output_format(line.strip()) for line in fin )
This assumes that you want to write the new content back to the original file:
with open('path/to/textFile.txt') as f:
content = f.readlines()
with open('path/to/textFile.txt', 'w') as f:
for line in content:
f.write('<p>' + line.strip() + '</p>\n')
with open('infile') as fin, open('outfile',w) as fout:
for line in fin:
fout.write('<P>{0}</P>\n'.format(line[:-1]) #slice off the newline. Same as `line.rstrip('\n')`.
#Only do this once you're sure the script works :)
shutil.move('outfile','infile') #Need to replace the input file with the output file
in you case, you should probably replace
data=f.read()
with:
data = '\n'.join("<p>%s</p>" % l.strip() for l in f)
use data=f.readlines() here,
and then iterate over data and try something like this:
for line in data:
line="<p>"+line.strip()+"</p>"
#write line+'\n' to a file or do something else
append the and <\p> for each line
ex:
data_new=[]
data=f.readlines()
for lines in data:
data_new.append("<p>%s</p>\n" % data.strip().strip("\n"))
You could use the fileinput module to modify one or more files in-place, with optional backup file creation if desired (see its documentation for details). Here's it being used to process one file.
import fileinput
for line in fileinput.input('testinput.txt', inplace=1):
print '<P>'+line[:-1]+'<\P>'
The 'testinput.txt' argument could also be a sequence of two or more file names instead of just a single one, which could be useful especially if you're using os.walk() to generate the list of files in the directory and its subdirectories to process (as you probably should be doing).

Python command isn't reading a .txt file

Trying to follow the guide here, but it's not working as expected. I'm sure I'm missing something.
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
file = open("C:/Test.txt", "r");
print file
file.read()
file.read()
file.read()
file.read()
file.read()
file.read()
Using the readline() method gives the same results.
file.readline()
The output I get is:
<open file 'C:/Test.txt', mode 'r' at 0x012A5A18>
Any suggestions on what might be wrong?
Nothing's wrong there. file is an object, which you are printing.
Try this:
file = open('C:/Test.txt', 'r')
for line in file.readlines(): print line,
print file invokes the file object's __repr__() function, which in this case is defined to return just what is printed. To print the file's contents, you must read() the contents into a variable (or pass it directly to print). Also, file is a built-in type in Python, and by using file as a variable name, you shadow the built-in, which is almost certainly not what you want. What you want is this:
infile = open('C:/test.txt', 'r')
print infile.read()
infile.close()
Or
infile = open('C:/test.txt', 'r')
file_contents = infile.read()
print file_contents
infile.close()
print file.read()
You have to read the file first!
file = open("C:/Test.txt", "r")
foo = file.read()
print(foo)
You can write also:
file = open("C:/Test.txt", "r").read()
print(file)

Categories

Resources