How to open a file, replace some strings, and save updates to the same file?

How to open a file, replace some strings, and save updates to the same file?

By : S.Meriem
Date : November 20 2020, 07:00 PM
Hope this helps I am trying to loop through all CSV files in a directory, do a find/replace, and save the results to the same file (same name). It seems like this should be easy, but I seem to be missing something here. Here is the code that I'm working with. , You need to open the file using 'r+' instead of 'w'. See below:
code :
import glob
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
    with open(str(fname), "r+") as f:
        newText = f.read().replace('|', ',').replace(' ', '')

Share : facebook icon twitter icon
Open a file and replace strings in C#

Open a file and replace strings in C#

By : Florian
Date : March 29 2020, 07:55 AM
Does that help I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close. , Can be done in one line:
code :
File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));
Open file, replace string save in different Directory

Open file, replace string save in different Directory

By : guan
Date : March 29 2020, 07:55 AM
Does that help Well, just use file_get_contents() and file_put_contents() like below and you'll not need any temp files:
code :

//open file and get data
$data = file_get_contents("path/to/sourcefile.php");

// do tag replacements or whatever you want
$data = str_replace("<tag1>", "<tag2>", $data);

//save it back:
file_put_contents("path/to/destinationfile.php", $data);

Replace strings and save file in Scala

Replace strings and save file in Scala

By : Richard S
Date : March 29 2020, 07:55 AM
Any of those help I have the following code where I am reading a file and replacing any occurences of "*.tar.gz" file with the new file name provided. Everything works fine and I can see the replaced changes in the console however I am not being able to write a new file with all the changes. , You forgot to write your modified lines into the new file:
code :
def modifyFile(newFileName: String, sourceFilePath: String, targetFilePath:String) {
    Source.fromFile(sourceFilePath).getLines().map { 
       _.replaceAll(".+\\.tar\\.gz", newFileName.concat(".tar.gz"))
Need to open a file and replace multiple strings

Need to open a file and replace multiple strings

By : Drmama Shania
Date : March 29 2020, 07:55 AM
should help you out Other answers give you better solutions to your problem. Mine concentrates on explaining why your code didn't work.
The core of your code is here:
code :

for (my $i = 0; $i < 42; $i++) {
    while(<IN>) {
        $_ =~ s/$old/$new/g;
        print OUT $_;
my $old    = 40960;
my $change = 1024;

while (<IN>) {
    # Easier way to write your loop
    for my $i ( 1 .. 42 ) {
        my $new = $old + $change;
        # Use \b to mark word boundaries
    # Print each output line only once
    print OUT $_;
How to use VBA to open msg file, edit it manually, save and replace the original msg file

How to use VBA to open msg file, edit it manually, save and replace the original msg file

By : user2887427
Date : March 29 2020, 07:55 AM
it fixes the issue The CreateItemFromTemplate method of the Application class creates a new Microsoft Outlook item from an Outlook template (.oft) and returns the new item. The second argument specifies the folder in which the item is to be created. If this argument is omitted, the default folder for the item type will be used (Draft for mail items).
code :
Sub CreateFromTemplate2() 
  Dim MyItem As Outlook.MailItem 
  Set MyItem = Application.CreateItemFromTemplate("C:\statusrep.oft", _ 
  ' or
  MyItem.SaveAs Environ("HOMEPATH") & "\My Documents\statusrep.oft", OlSaveAsType.olTemplate 
End Sub
Related Posts Related Posts :
  • Removing non-breaking spaces from strings using Python
  • Is there a way to backup everything in an app-engine blobstore?
  • Process a set of files from a source directory to a destination directory in Python
  • How to know if optparse option was passed in the command line or as a default
  • Rewriting a for loop in pure NumPy to decrease execution time
  • Comparing a time delta in python
  • Find next lower item in a sorted list
  • MySQLdb not INSERTING, _mysql does fine
  • Scipy Negative Distance? What?
  • What are the common patterns in web programming?
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk