[英]Read, manipulate and save text file
全部,
我正在尝试读取每 20 分钟下载到某个文件夹的文本文件,检查它,操作它并将其移动到另一个位置以进行进一步处理。 基本上,我想检查传入的每个文件,检查字符串是否包含“0.00”值,如果是,则删除该特定字符串。 每个文件有两个字符串。 我设法操作了具有给定名称的文件,但现在我需要对具有变量名称的文件执行相同操作(标题中包含时间戳)。 一次需要处理一个文件。
这是我到目前为止得到的:
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)
有效的是 def-function 和两个“with open...”代码。 我在这里做错了什么?
另外,我可以使用 open() 函数将文件写入另一个目录吗?
提前致谢!
您的代码看起来基本没问题。 我不认为你的列表理解方法确实删除了字符串。 您可以使用 Open() 写入不同的文件夹。 这应该对你有用:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.