Can't read a file with w+ [duplicate] - python

This question already has answers here:
Difference between modes a, a+, w, w+, and r+ in built-in open function?
(9 answers)
Closed 1 year ago.
heres the code
doc = open(path, 'w+')
lines = []
i = 0
for line in doc:
lines.append(line)
i += 1
if i == 1:
money = int(line)
print(lines)
heres what is returns
[]
the text file contains one line that says "1000"
I tried to resolve the issue by opening it with r, close it, and open it again with w. But for some reason it just deletes all of the text in the file when I try to write anything.

opening it with w+ will overwrite the existing file with a new empty file (which you can then both write and read from) ...
you probably want to open it with a+ (to append) this will put the pointer at the end of the file and then to read before that you will need to use open_file.seek(0) (to go to the beginning of the file)

Related

Why do i get an empty file when trying to edit it using pyhon? [duplicate]

This question already has answers here:
Difference between modes a, a+, w, w+, and r+ in built-in open function?
(9 answers)
Closed 1 year ago.
I am trying to edit a text file that is html using python. When printing it, it gives an empty file. Why it gets empty? I tried to print it because I don't know how to return it.
Here's the code:
import bleach
with open ('index1.txt','w') as f: #to open the file that contains html markups
bleach.clean(
'f',
tags=['p'],
attributes=['style'],
styles=['color'],
)
f=open('index1.txt')
content = f.read()
f.close()
print(content)
It becomes empty because you open file for writing with 'w' and thus make it empty as per documentation - just change it to 'r' or 'a'
It would remain empty because you're just creating a file & not writing anything on it.

How to read each line in a file backwards using Python [duplicate]

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 3 years ago.
I'm trying to read a file (example below), line by line, backwards using Python.
abcd 23ad gh1 n d
gjds 23iu bsddfs ND31 NG
Note: I'm not trying to read the file from the end to the beginning, but I want to read each line starting from the end, i.e d for line 1, and NG for line 2.
I know that
with open (fileName) as f:
for line in f:
reads each line from left to right, I want to read it from right to left.
Try this:
with open(fileName, 'r') as f:
for line in f:
for item in line.split()[::-1]:
print(item)
If your file is not too big, you can read lines in reverse easily
with open(fileName) as f:
for line in reversed(f.readlines()):
# do something
Otherwise, I believe you'd have to use seed.

Manipulating text files: Line deletion if keyword is found [duplicate]

This question already has answers here:
How to delete a specific line in a file?
(17 answers)
Closed 6 years ago.
So I'm attempting to clean up a text file that I have (it is actually a region file which can be loaded into the astronomy fits viewer DS9). I would like to remove/delete the entirety of any line/(s) which contain the keyword "red" in them, for an example:
image;circle(2384.21957861,231.579450647,10.3410929712) # color = red text = {24}
Would anyone know how this could be accomplished within python?
Open an outfile (outfile.txt) for writing, and open your input file (textfile.txt), going line by line through the input file scanning for the keyword (red). If red is not in the line it writes it to the outfile.
with open('outfile.txt', 'w') as o:
with open('textfile.txt') as f:
for line in f.readlines():
if 'red' not in line:
o.write(line)
Make sure the files are within the same directory as the python script.
Based on this answer suggested by #algor, you coul try:
f = open("textfile.txt","r+")
d = f.readlines()
f.seek(0)
for line in d:
if 'red' not in line:
f.write(i)
f.truncate()
f.close()

How to prevent print from overwriting a text file? [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 8 years ago.
This code actually overwrite the pre-existing content of out.txt, is there a way to make it print in the next line ?
with open(r'C:\out.txt', "w") as presentList:
print("Hello", file=presentList)
Use "a" instead of "w".
This appends new text at the end.
I think you'll want to open with "r+" instead (opening with "w" overwrites the file!). If you aren't partial to using with, you can do
f = open("C:/out.txt","r+")
f.readlines()
f.write("This is a test\n")
f.close()
The f.readlines() will ensure that you write to the end of the file instead of overwriting the first line if you need to write more. As the other person said, you can also open with "a" too

How to remove line from the file in python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Deleting a specific line in a file (python)
I need to delete the line contains number '2' from the file f=
2 3
5 6
7 2
4 5
When you want to edit a file, you make a new file with the correct data and then rename the new file as the old file. This is what serious programs like your text editor probably do. (Some text editors actually do even weirder stuff, but there's no use going into that.) This is because in many filesystems the rename can be atomic, so that under no circumstances will you end up with the original file being corrupted.
This would lead to code to the effect of
with open(orig_file) as f, open(working_file, "w") as working:
# ^^^ 2.7+ form, 2.5+ use contextlib.nested
for line in f:
if '2' not in line: # Is this exactly the criterion you want?
# What if a line was "12 5"?
working.write(line)
os.rename(working_file, orig_file)
You may want to use orig_file + '~' or the tempfile module for generating the working file.
with open('f', 'r+') as f:
data = ''.join(filter(lambda l: '2' not in l.strip().split(' '), f))
f.seek(0)
f.truncate(0)
f.write(data)
import fileinput
for line in fileinput.input('f',inplace =1):
line = line.strip()
if not '2' in line:
print line

Categories