简体   繁体   中英

Read, manipulate and save text file

All,

I'm trying to read text files that are being downloaded every 20 min in to a certain folder, check it, manipulate it and move it to another location for further processing. Basically, I want to check each file that comes in, check if a string contains a "0.00" value and if so, delete that particular string. There are two strings per file. I managed to manipulate a file with a given name, but now I need to do the same for files with variable names (there is a timestamp included in the title). One file will need to be processed at a time.

This is what I got so far:

import os

path = r"C:\Users\r1.0"
dir = os.listdir(path)

def remove_line(line, stop):
    return any([word in line for word in stop])

stop = ["0.00"]
for file in dir:
    if file.lower().endswith('.txt'):
        with open(file, "r") as f: 
            lines = f.readlines()

        with open(file, "w") as f:
            for line in lines:
                if not remove_line(line, stop):
                    f.write(line)

What works are the def-function and the two "with open..." codes. What am I doing wrong here?

Also, can I write a file to another directory using the open() function?

Thanks in advance!

Your code looks mostly fine. I don't think your list comprehension method does remove the string though. You can write to a different folder with Open(). This should do the trick for you:

import os

path = r"C:\Users\r1.0"
dir = os.listdir(path)

stop = ["0.00"]
for file in dir:
    if file.lower().endswith('.txt'):
        with open(file, "r") as f: 
            lines = f.readlines()
        # put the new file in a different location
        newfile = os path.join("New", "directory", file)
        with open(newfile, "w") as f:
            for line in lines:
                if stop in line: #check if we need to modify lime
                      #modify line here
                      #this will remove stop from the line
                      line.replace(stop, "")
                # Regardless of whether the line has changed, we need to write it out. 
                f.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM