Python: How to remove specific string from a file? [duplicate] - python

This question already has answers here:
How to bypass memory error when replacing a string in a large txt file?
(2 answers)
Closed 1 year ago.
I have a file, for example, "data.txt" with "1234567890" text inside. How can my program delete "678", so that "data.txt" will consist of "1234590"?
In addition, data.txt is a really heavy file. So you can't use pure read() or readlines().
I want to use only python tools, so "shell" is not an option.

You can do something like following:
with open("Stud.txt", "r") as fin:
with open("out.txt", "w") as fout:
for line in fin:
fout.write(line.replace('678', ''))

Related

\n changes to \\n after reading csv file in python [duplicate]

This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Quoting backslashes in Python string literals [duplicate]
(5 answers)
Closed 27 days ago.
I am reading a file that has \n as a new line character. But when I read it using pandas, it appears as \\n. How can I avoid this?
I tried both pandas and python csv but nothing worked
in pandas, you can set lineterminator to '\n' and that should work. Alternatively, you can use the csv module in python to read your csv file as follows :
import csv
with open(filepath, newline='', encoding='utf-8') as f:
reader = csv.reader(f, delimiter='\n')
for row in reader:
print(row)

How do I clear all the contents of my file before I write on it? [duplicate]

This question already has answers here:
How to erase the file contents of text file in Python?
(13 answers)
Closed last year.
I would like to delete all the contents of my file first, then write on it. How do I do that with a simple file? `
fileHandle = open("file.txt","w")
fileHandle.write(randomVar)
fileHandle.close()
What you need is to open the file in a truncating mode. These are "w" and "w+". Your current code uses "w", so it should work fine!
In python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
https://stackoverflow.com/a/2769090/17773920
whenever using open(filename,'w') all the content of the data will be overwritten.
If you wish to add content to the file you should be using open(filename,'a').
In addition, I would recommend opening the file using
with open('filename','mode') as f: your code here
as it will provide context manager, making sure the file will closed when you are done with it.

Is it possible to ensure a file is closed without assigning it to a variable? [duplicate]

This question already has answers here:
Is there a need to close files that have no reference to them?
(6 answers)
Does reading an entire file leave the file handle open?
(4 answers)
Closed 1 year ago.
I am reading some data from a .txt file in Python using the following:
fileData = open("file.txt", "rb").read()
I know that you should always close opened files, and I assume in this case the file remains open. Is there a way to close the file without assigning it to a variable?
I'd like to avoid:
openedFile = open("file.txt", "rb")
fileData = openedFile.read()
openedFile.close()
And also:
with open("file.txt", "rb") as openedFile:
fileData = openedFile.read()
It might not be possible, in which case okay, but just making sure.
No, it's not possible. The with statement version is the idiomatic way to write it.
Though I would shorten openedFile to file or even f. Rule of thumb: The smaller the scope of a variable the shorter its name can be. Save the long names for long-lived identifiers.
with open("file.txt", "rb") as file:
data = file.read()

Why my file end up blank when I try to remove characters? [duplicate]

This question already has answers here:
replacing text in a file with Python
(7 answers)
What is the best way to modify a text file in-place?
(4 answers)
Closed 1 year ago.
I followed this subject here because I want to remove the <br /> that are in my output text file.
So my code is the following one :
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt', 'r') as infile, open('comments_'+video_id+'.txt', 'w') as outfile:
temp = infile.read().replace("<br />", "")
outfile.write(temp)
If I remove this function call my file has content, but after I call this function my file is empty. Where did I do something wrong ?
Opening a file in w mode truncates the file first. So there's nothing to read from the file.
Read the file first, then open it for writing.
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt', 'r') as infile:
temp = infile.read().replace("<br />", "")
with open('comments_'+video_id+'.txt', 'w') as outfile:
outfile.write(temp)

Python - Write list to text file with \n from re.findall [duplicate]

This question already has answers here:
Writing a list to a file with Python, with newlines
(26 answers)
Closed 5 years ago.
In reference to a previous question Python Regex - Capture match and previous two lines
I am try to write this match to a text file but it seems to write all the matches on 1 line.
Tried these combinations with no luck
output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', f.read())
myfilename.write(str(list(output) + '\n')) # gives me TypeError: can only concatenate list (not "str") to list
myfilename.write(str(output)) # writes to one line
Would I need a for loop to iterate each index to a new line, or am I missing something, it should be matching the CRLLF and keep the original format correct?
You could use
with open ("file_here.txt", "r") as fin, open("output.txt", "w") as fout:
output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', fin.read())
fout.write("\n".join(output))

Categories

Resources