背景:我正在尝试自动化工作流程的某些部分。我采取的手动步骤:我得到一张在文本文件中更改ID的票证。我必须浏览一个网络共享文件夹,创建文件的备份,将复制的文件推入存档文件夹,并使用票证中的ID编辑现有文件。
我试图创建的内容:一个小程序会问我想要更改什么ID(文本文件中有预先存在的ID(,然后它会进入文件并找到匹配项。然后我想让程序问我想把ID改成什么。我想让该程序用我的输入编辑现有文件,保存它,然后关闭它。
到目前为止,我有以下代码完成了第一部分(复制文件并将其推入归档文件夹(。我有第二个功能,但我一直在使用。我知道第二个函数不起作用,但我希望其他人能告诉我应该尝试什么。我看过fileinput模块,但我读到它不是最好的模块,我应该尝试在没有fileinput的情况下编程。
代码:
import shutil
import datetime
import os
import fileinput
original_file = "\network\path\to\file"
def date_rename_file():
todays_date = datetime.datetime.now()
stripped_time = todays_date.strftime('%Y%m%d')
shutil.copyfile(original_file, "\network\path\to\backupfolder\device_"+str(stripped_time)+".txt")
def device_id_replace():
original_id = input("What device ID are you needing to replace?")
new_id = input("What is the new device ID?")
with open(original_file, 'w') as devicetxt:
for line in devicetxt:
print(line)
if original_id in line:
print("Found "+original_id)
date_rename_file()
device_id_replace()
谢谢,可以随意删除我的代码:(我仍在学习,如果有任何意见,我将不胜感激。此外,如果我遗漏了任何相关信息,请随时告诉我
你可以试试这个:
def device_id_replace():
original_id = input("What device ID are you needing to replace?")
new_id = input("What is the new device ID?")
with open(original_file, 'r+') as devicetxt: #r+ is for read and write
string = devicetxt.read() #read into one string
string = string.replace(original_id, new_id) #replacement
devicetxt.truncate(0) #To clear contents of file before writeback
devicetxt.seek(0) #Put the file's current position at 0
devicetxt.write(string) #writeback to file
此外,最好将original_file
作为字符串传递给函数。参见下面的编辑代码:
import shutil
import datetime
import os
import fileinput
original_file = "\network\path\to\file"
def date_rename_file(filepath):
todays_date = datetime.datetime.now()
stripped_time = todays_date.strftime('%Y%m%d')
shutil.copyfile(filepath, "\network\path\to\backupfolder\device_"+str(stripped_time)+".txt")
def device_id_replace(filepath):
original_id = input("What device ID are you needing to replace?")
new_id = input("What is the new device ID?")
with open(filepath, 'r+') as devicetxt: #r+ is for read and write
string = devicetxt.read() #read into one string
string = string.replace(original_id, new_id) #replacement
devicetxt.truncate(0) #To clear contents of file before writeback
devicetxt.seek(0) #Put the file's current position at 0
devicetxt.write(string) #writeback to file
date_rename_file(original_file)
device_id_replace(original_file)
试试这个:
original_file = ""\network\path\to\file""
def device_id_replace(filepath):
original_id = input("What device ID are you needing to replace?")
new_id = input("What is the new device ID?")
with open(filepath, 'r') as devicetxt:
new_content = []
for line in devicetxt:
new_content.append(line.replace(original_id, new_id))
with open(filepath, "w") as devicetxt:
for line in new_content:
devicetxt.write(line)
device_id_replace(original_file)
@ycx的答案在过去不起作用。所以我修复了你的旧代码:
original_file = "test.txt"
def device_id_replace(filepath):
original_id = input("What device ID are you needing to replace?")
new_id = input("What is the new device ID?")
with open(filepath, 'r+') as devicetxt: #r+ is for read and write
contents = devicetxt.readlines() #put all lines into a list
for line_i, line in enumerate(contents):
if original_id in line:
contents[line_i] = line.replace(original_id, new_id) # CHANGED LINE
devicetxt.truncate(0)
devicetxt.seek(0)
devicetxt.writelines(contents) #writeback to file
device_id_replace(original_file)
这里有几个选项,如果您使用的是Unix/Unix之类的内部工具,可以使用sed,也可以在旧文件的基础上创建一个新文件。
- 读取所有文件
- 替换引用
- 重写所有行
这是一个蟒蛇版本
with open(filepath) as f:
transformedLines = [line.replace(old, new) if (old in line) else (line) for line in f]
with open(filepath, 'w') as f:
f.writelines(transformedLines);
一个不那么Python的版本是类似的:
transformedLines = []
with open(filepath) as f:
for line in f:
if old in line:
transformedLines.append(line.replace(old, new))
else:
transformedLines.append(line)
一种功能性的方式(尽管效率很低(可以用地图完成:
transformedLines = list(map(lambda line : line.replace(old, new), f.readlines()))
如果你的文件不是很大,这应该没问题,否则你将不得不考虑使用不同类型的数据存储,比如DB。
您的方法目前运行良好,但您希望以读取模式打开它,对于每一行都将其附加到一个新列表中,如果找到您的id,则改为附加新行。
将新数组写入在写入模式下打开的文件,这将擦除内容。