How can I make this work to delete values from my txt file? I have an 11 line file of 4 digit numbers, I can add but am stuck on deleting.
def delete_file(string_in):
print("deleted_from_file")
with open('test.txt', 'a+') as f:
d = f.readlines()
f.seek(11)
for i in d:
if i != " item = {} ":
f.write(i)
f.close()
a+ mode means to write at the end of the file. So the seek has no effect, it always writes the lines after all the existing lines.
It would be easier to just open the file separately for reading and writing. Otherwise you also need to truncate the file after all the writes.
BTW, you don't need to use f.close() when you use with -- it automatically closes (that's the whole point).
The lines returned by readlines() end with newlines, you need to strip those off before comparing with the string.
def delete_file(string_in):
print("deleted_from_file")
with open('test.txt', 'r') as f:
d = f.readlines()
with open('test.txt', 'w') as f:
for i in d:
if i.rstrip('\n') != " item = {} ":
f.write(i)
You can store all the needed lines into a list using a list comprehension, and then write the lines into the file again after the file empties out:
def delete_file(string_in):
print("deleted_from_file")
with open('test.txt', 'r') as f:
d = [i for i in f if i.strip('\n') != " item = {} "]
with open('test.txt', 'w') as f:
f.write(''.join(d))
Related
I had to redo my questions because it made everyone focus on the wrong word
Sorry about this guys but I did put that I have 100 rows with different code names
This is my working code
with open("file1.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "nman" not in line:
f.write(line)
f.truncate()
inside the text file
Before = file1.txt
"nman": "afklafjlka"
"prvr": "521.0.25",
"prvrfi": "1.18.3",
RESULTS = file1.txt
"prvr": "521.0.25",
"prvrfi": "1.18.3",
As you can see in my result the code "nman" was removed the whole row was removed
I made something in batch for this, but it's way to slow
I used in batch this script
findstr /V "\<nman\> \<prvr\>" file1.txt > file2.txt
So my end result for the updated script should be able to read many different code names just like my batch script
with open("file1.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "nman" "prvr" not in line: < --------
f.write(line)
f.truncate()
or something like this
to_delete = ["nman", "prvr"] < ------
with open("file1.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if to_delete not in line: < --------
f.write(line)
f.truncate()
Working Script Thank you
with open("file1.txt", 'r') as f:
lines = f.readlines()
to_delete = ["nman",
"prvr"]
new_lines = []
for l in lines:
for d in to_delete:
if d in l:
l = ""
break
new_lines.append(l)
with open("file2.txt", 'w') as file2:
file2.writelines(new_lines)
with open("file1.txt", 'r') as f:
lines = f.readlines()
to_delete = ["nman", "prvr"]
new_lines = []
for l in lines:
for d in to_delete:
if d in l:
l = ""
break
new_lines.append(l)
with open("file2.txt", 'w') as file2:
file2.writelines(new_lines)
If there's a rule you can delete rows in a single wipe with regular expressions.
This one deletes all the rows that start with "code followed by a number.
from re import sub
with open('file1.txt', 'r') as f:
text = f.read()
with open('file1.txt', 'w') as f:
f.write(sub('("code\d+".*(\n|))','',text))
If there's a rule but you don't want to use RegEx or you don't know how to use them, then you can use a function to check if a row is good or bad
from re import search
code_list = ['1', '2', '3']
with open('file1.txt', 'r') as f:
text = f.readlines()
with open('file1.txt', 'w') as f:
f.writelines([_ for _ in text if not any([search(f'code{i}', _) for i in code_list])])
Or within a range:
from re import search
with open('file1.txt', 'r') as f:
text = f.readlines()
with open('file1.txt', 'w') as f:
f.writelines([_ for _ in text if not any([search(f'code{i}', _) for i in range(100)])])
Given Input File:
"nman": "afklafjlka"
"prvr": "521.0.25",
"prvrfi": "1.18.3",
| acts like a boolean OR in regex
import re
words = ['"nman"', '"prvr"'] # USE THE '""' OR YOU MAY DELETE MORE THAN EXPECTED
words = '|'.join(words) # == "nman"|"prvr"
with open('test.txt', 'r+') as f:
# Marker used by truncate.
f.seek(0)
# Adds lines to the list if a regex match is NOT found.
# Matching the OR statement we created earlier.
lines = [x for x in f.readlines() if not re.match(words, x)]
# Writes all the lines we found to the file.
f.writelines(lines)
# Cuts off everything we didn't add.
f.truncate()
Output:
"prvrfi": "1.18.3",
So as the title suggests I'm trying to write an array to a file, but then I need to recall that array and append more to it and then write it back to the same file, and then this same process over and over again.
The code I'm have so far is:
c = open(r"board.txt", "r")
current_position = []
if filesize > 4:
current_position = [c.read()]
print(current_position)
stockfish.set_position(current_position)
else:
stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
#There is a lot more code here that appends stuff to the array but I don't want to #add anything that will be irrelevant to the problem
with open('board.txt', 'w') as filehandle:
for listitem in current_position:
filehandle.write('"%s", ' % listitem)
z = open(r"board.txt", "r")
print(z.read())
My array end up looking like this when I read the file
""d2d4", "d7d5", ", "a2a4", "e2e4",
All my code is on this replit if anyone needs more info
A few ways to do this:
First, use newline as a delimiter (simple, not the most space efficient):
# write
my_array = ['d2d4', 'd7d5']
with open('board.txt', 'w+') as f:
f.writelines([i + '\n' for i in my_array])
# read
with open('board.txt') as f:
my_array = f.read().splitlines()
If your character strings all have the same length, you don't need a delimiter:
# write
my_array = ['d2d4', 'd7d5'] # must all be length 4 strs
with open('board.txt', 'w+') as f:
f.writelines(my_array)
# read file, splitting string into groups of 4 characters
with open('board.txt') as f:
in_str = f.read()
my_array = [in_str[i:i+4] for i in range(0, len(in_str), 4)]
Finally, consider pickle, which allows writing/reading Python objects to/from binary files:
import pickle
# write
my_array = ['d2d4', 'd7d5']
with open('board.board', 'wb+') as f: # custom file extension, can be anything
pickle.dump(my_array, f)
# read
with open('board.board', 'rb') as f:
my_array = pickle.load(f)
as you're reusing the file to append data to it, you should replace:
open('board.txt', 'w')
with
open('board.txt', 'a')
a denotes append mode. Which will not overwrite what you have in your file, it will append to it.
I have a problem with a code in python. I want to read a .txt file. I use the code:
f = open('test.txt', 'r') # We need to re-open the file
data = f.read()
print(data)
I would like to read ONLY the first line from this .txt file. I use
f = open('test.txt', 'r') # We need to re-open the file
data = f.readline(1)
print(data)
But I am seeing that in screen only the first letter of the line is showing.
Could you help me in order to read all the letters of the line ? (I mean to read whole the line of the .txt file)
with open("file.txt") as f:
print(f.readline())
This will open the file using with context block (which will close the file automatically when we are done with it), and read the first line, this will be the same as:
f = open(“file.txt”)
print(f.readline())
f.close()
Your attempt with f.readline(1) won’t work because it the argument is meant for how many characters to print in the file, therefore it will only print the first character.
Second method:
with open("file.txt") as f:
print(f.readlines()[0])
Or you could also do the above which will get a list of lines and print only the first line.
To read the fifth line, use
with open("file.txt") as f:
print(f.readlines()[4])
Or:
with open("file.txt") as f:
lines = []
lines += f.readline()
lines += f.readline()
lines += f.readline()
lines += f.readline()
lines += f.readline()
print(lines[-1])
The -1 represents the last item of the list
Learn more:
with statement
files in python
readline method
Your first try is almost there, you should have done the following:
f = open('my_file.txt', 'r')
line = f.readline()
print(line)
f.close()
A safer approach to read file is:
with open('my_file.txt', 'r') as f:
print(f.readline())
Both ways will print only the first line.
Your error was that you passed 1 to readline which means you want to read size of 1, which is only a single character. please refer to https://www.w3schools.com/python/ref_file_readline.asp
I tried this and it works, after your suggestions:
f = open('test.txt', 'r')
data = f.readlines()[1]
print(data)
Use with open(...) instead:
with open("test.txt") as file:
line = file.readline()
print(line)
Keep f.readline() without parameters.
It will return you first line as a string and move cursor to second line.
Next time you use f.readline() it will return second line and move cursor to the next, etc...
What I am trying to do is remove the quotes while writing the data to a new CSV file.
I have tried using s.splits, and .replaces with no luck. Can you guys point me in the right direction?
Current Code:
def createParam():
with open('testcsv.csv', 'r') as f:
reader = csv.reader(f)
csvList = list(reader)
for item in csvList:
os.mkdir(r"C:\Users\jefhill\Desktop\Test Path\\" + item[0])
with open(r"C:\Users\jefhill\Desktop\Test Path\\" + item[0] + r"\prm.263", "w+") as f:
csv.writer(f).writerow(item[1:])
f.close
Data within testcsv.csv:
0116,"139,data1"
0123,"139,data2"
0130,"35,data678"
Data output when script is ran (in each individual file):
"139,data1"
"139,data2"
"35,data678"
Data I would like:
139,data1
139,data2
35,data678
You can use str.replace to replace the " (double quotes) with '' (null).
Then split and print all but first item in the list.
with open('outputfile.csv', w) as outfile: # open the result file to be written
with open('testcsv.csv', 'r') as infile: # open the input file
for line in infile: # iterate through each line in input file
newline = line.replace('"', '') # replace double quotes with no space
outfile.write(newline.split(',',maxsplit=1)[1]) # write second element to output file after splitting the newline once
You don't need f.close() when you use with open...
Below is the input file sample_text.txt
10001ScottTiher100040
10002ScoteTijer100042
10003ScotrTieer100043
10004ScotfTiler100044
10005ScotyTiper100046
10006ScotlTioer100047
10007ScotiTiwer100049
I need to save this in the same file as below, can you please help me on this....
10001,Scott,Tiher,100040
10002,Scote,Tijer,100042
10003,Scotr,Tieer,100043
10004,Scotf,Tiler,100044
10005,Scoty,Tiper,100046
10006,Scotl,Tioer,100047
10007,Scoti,Tiwer,100049
I have tried the below code, but unable to save the b in new file or same file
with open('D:\Programs\python\sql_test.txt','r+') as f:
for line in f:
for word in line.split():
b = str(word[0:5])+ ',' + str(word[5:10]) + ',' + str(word[10:15])+','+ str(word[15:21])
print(b)
You can open two file with with context manager: One for input, The other for output.
with open("ifilename", 'r') as ifile, open("ofilename", 'w') as ofile:
for line in ifile:
print(','.join([line[0:5], line[5:10], line[10:15], line[15:]]), file=ofile)
This is one approach
Demo:
res = []
with open(filename, "r") as infile:
for i in infile.readlines():
val = i.strip()
res.append([val[:5], val[5:10], val[10:15], val[15:]])
with open(filename, "w") as outfile:
for i in res:
outfile.write(", ".join(i) + "\n")
Maybe the reg is simple to do this:
import re
with open("origin.txt", 'r') as in_fd, open("new.txt", 'w') as out_fd:
for line in in_fd.readlines():
match = re.match(r"([0-9]+)([a-z]+)([0-9]+)", line, re.I)
out_fd.write(','.join(match.groups())+ '\n')
You have to use f.write(b) to save b in your file
Very late answer
Your early solution is better without the second loop.
As you know, you cannot have a file with the read option (r) and also the write (w) option.
The option r+, append the transformed data to the end of the file. For the sake of the exercice, we will not use r+
Here, we use f to read the file and f1 to write the results, ending with a formatting with a \n to jump lines.
In [3]: with open('split.txt','r') as f, open('split2.txt','w') as f1: #one file for read and the other one for saving the result
...: for line in f:
...: output = str(line[0:5])+ ',' + str(line[5:10]) + ',' + str(line[10:15])+','+ str(line[15:21])
...: f1.write("{0}{1}".format(output,"\n")) #outputting with \n to jump to the next line for any new line