I know there are a lot of questions about file.read() but I dont think any of them answer this....
Can someone tell me why, if I read a file with say 12 lines, in the interpreter and print it by just typing in filename.read(), it is presented on one continuous line with the EOL character to signify each line?
Then, if I do the same but create define an object, say file-output = filename.read(), and then print that object, it then prints out as it appears in the file?
Does what I said make sense????
Many thanks
Related
I don't know how it works and can't see answer for this. I wanted to replace comma to dot in file. So i write this code:
with fileinput.FileInput("tabela.txt", inplace=True, backup='.bak') as file:
for line in file:
line = line.replace(',', '.')
and i thought it should work. But it didn't. But when i replace line=line.replace(...) to:
print(line.replace(",", "."), end='')
it works fine. Can someone explain why line=line.replace(...) doesn't work but print(...) which should just print something (and it even doesn't print lines) replace my comma to dots?
Thanks for answers
EDIT: I said that print should just print something, but ofc it's not true (i think) because as I can see it replace strings in my file in some reason with replace function.
From the docs
Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).
So the library is built with the use-case of "get input in a variable and output to standard out" in mind. Hence, print is the intended mechanism.
Simply assigning to a local variable and then discarding the result does nothing. It replaces the string in memory and then... garbage collects it soon after. The real-world analogy would be doing a bunch of math homework on a sheet of paper and then putting the paper in the trash rather than submitting it; my teacher isn't going to grade what I throw away.
I want to write to a file in tabular format and following is code I have written till now.
file_out=open("testing_string","w")
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:12}".format("Check"))
file_out.write("{0:12}".format("_5"))
file_out.close()
Testing_string looks like this.
TUPLE LOGFILE STATUS FSDB STATUS
Check _5
Problem is I want _5 to be with check. Please see that I cannot concatenate check with _5 as check is printed first in file then depeding on some logic I fill LOGFILE STATUS FSDB STATUS. If I am unable to fill status then I check if I have to append _5 or not. so due to this I cannot concatenate string.
How to then print _5 right next to Check?
In a perfect world, you wouldn't do what is given in the below answer. It is hacky and error-prone and really weird. In a perfect world you would figure out how to write out what you want before you actually write to disk. I assume the only reason you are even considering this is that you are maintaining some old and crusty legacy code and cannot do things "the right way".
This is not the most elegant answer, but you can use the backspace character to overwrite something previously written.
with open('test.txt', 'w') as file_out:
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:12}".format("Check"))
backup_amount = 12 - len("Check")
file_out.write("\b" * backup_amount)
file_out.write("{0:12}".format("_5"))
Output:
TUPLE LOGFILE STATUS FSDB STATUS
Check_5
This only works in this specific case because we are completely overwriting the previously written characters with new characters - the backspace nearly backs up the cursor but does not actually overwrite the previously written data. Observe:
with open('test.txt', 'w') as f:
f.write('hello')
f.write('\b\b')
f.write('p')
Output:
helpo
Since we backspaced two characters but only wrote one, the original second character still exists. You would have to manually write ' ' characters to overwrite these.
Because of this caveat, you will probably have to start messing with the length of the format codes (i.e. '{0:12}' might need to become '{0:5}' or something else) when you add '_5'. It's going to become messy.
The problem is that you are specifying 12 characters for Check. Try this:
file_out=open("testing_string","w")
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:5}".format("Check"))
file_out.write("{0:7}".format("_5"))
file_out.close()
I have this line in a .txt file:
I just got home.\nDid you make lunch?\nOh, I see...
It's just one line, it's formatted like this for a game, so it is exactly like this, with the \n's.
What I need is that when I print this, after I store it into a variable or list, to print it on multiple lines, respecting the \n. Like this:
I just got home.\n
Did you make lunch?\n
Oh, I see...
I can't think of a way to modify the output to make a new line after the program displays each \n. How would I do this?
Using of str.replace() function would be enough:
s="I just got home.\nDid you make lunch?\nOh, I see..."
print(s.replace("\n", "\\n\n"))
The output:
I just got home.\n
Did you make lunch?\n
Oh, I see...
I have a long text file that I am trying to pull certain strings out of. The length of these strings are variable with the text file but are always located after certain identifiers. So for example say my text file looks like this:
junk text...
Name:
Age:
Robert
twenty
four.
junk text...
I always know that the "Robert" string is located at "Age:\n\n" but I am not sure how long it is only that it will end at a "\n\n" and the same principle with the "twenty four." string. I have tried using
namepos1 = string.find("Age:")
namepos2 = namepos1 + 6
this will give the starting location of the string I want but I do not know how to save it into a variable such that it always saves the whole string up to the two new line characters. If it was a set length and not variable I think I could use:
name = string[namepos2:length]
but any help would be greatly appreciated. I may have to go about doing it completely different, but this is the first way I have thought about it and tried to do it.
Thanks!
You could do this by finding age, then moving forward your cursor two lines if you would like to do that, if you want the entire section of text after the "junk", and you know how long that text is, this would also work:
lookup = 'age'
lines=[]
with open('C:/Users/Luke/Desktop/Summer 2016/Programs/untitled5.txt') as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
lines.append(num+2)
ofile=open('C:/Users/Luke/Desktop/Summer 2016/Programs/untitled5.txt')
line=ofile.readlines()
interestinglines=''
for i in range(len(lines)):
interestinglines+=(line[lines[i]]+'\n')
you may need to tinker with it a bit, but I believe this should reproduce mostly what you're looking for. The '\n' is added onto the line[lines[i]] so that you may save it to a new file.
After you found the location in string, you can split the String by \n\n and get the first item.
s = file_str[namepos2 :]
name = s.split('\n\n')[0]
As an attorney I am a total newbie in programimg. As an enthusiastic newbie, I learn a lot. (what are variables, ect.) ).
So I'm working a lot with dir() and I'm looking into results. It would by nicer if I could see the output in one or more columns. So I want to write my first program which write for example dir(sys) in a output file in columns.
So far I've got this:
textfile = open('output.txt','w')
syslist = dir(sys)
for x in syslist:
print(x)
The output on display is exactly what I want, but when I use the .write like:
textfile = open('output.txt','w')
syslist = dir(sys)
for x in syslist:
textfile.write(x)
textfile.close()
The text is in lines.
Can anyone pleaase help me, how to write the output of dir(sys) to a file in columns?
If I can ask you, please write the easysiet way, because I really have to look almost after for every word you write in documentation. Thanks in advance.
print adds a newline after the string printed by default, file.write doesn't. You can do:
for x in syslist: textfile.write("%s\n" % x)
...to add newlines as you're appending. Or:
for x in syslist: textfile.write("%s\t" % x)
...for tabs in between.
I hope this is clear for you "prima facie" ;)
The other answers seem to be correct if they guess that you're trying to add newlines that .write doesn't provide. But since you're new to programming, I'll point out some good practices in python that end up making your life easier:
with open('output.txt', 'w') as textfile:
for x in dir(sys):
textfile.write('{f}\n'.format(f=x))
The 'with' uses 'open' as a context manager. It automatically closes the file it opens, and allows you to see at a quick glance where the file is open. Only keep things inside the context manager that need to be there. Also, using .format is often encouraged.
Welcome to Python!
The following code will give you a tab-separated list in three columns, but it won't justify the output for you. It's not fully optimized so it should be easier to understand, and I've commented the portions that were added.
textfile = open('output.txt','w')
syslist = dir(sys)
MAX_COLUMNS = 3 # Maximum number of columns to print
colcount = 0 # Track the column number
for x in syslist:
# First thing we do is add one to the column count when
# starting the loop. Since we're doing some math on it below
# we want to make sure we don't divide by zero.
colcount += 1
textfile.write(x)
# After each entry, add a tab character ("\t")
textfile.write("\t")
# Now, check the column count against the MAX_COLUMNS. We
# use a modulus operator (%) to get the remainder after dividing;
# any number divisible by 3 in our example will return '0'
# via modulus.
if colcount % MAX_COLUMNS == 0:
# Now write out a new-line ("\n") to move to the next line.
textfile.write("\n")
textfile.close()
Hope that helps!
I'm a little confused by your question, but I imagine the answer is as simple as adding in tabs. So change textfile.write(x) to textfile.write(x + "\t"), no? You can adjust the number of tabs based on the size of the data.
I'm editing my answer.
Note that dir(sys) gives you an array of string values. These string values do not have any formatting. The print x command adds a newline character by default, which is why you are seeing them each on their own line. However, write does not. So when you call write, you need to add in any necessary formatting. If you want it to look identical to the output of print, you need to add in write(x + "\n") to get those newline characters that print was automatically including.