可以从文本文件中重写行而不必使用Python关闭并重新打开文件吗?

时间:2018-01-03 14:37:03

标签: python pycharm

上下文

我正在构建一个生成器,用于从客户自制的HMI导入大量的sensordata进行分析。我将所有由HMI收集的数据提取到一个大文本文件中。

我有一个文本文件,其中包含如下目录:

Testfile.txt
/MDS/10_LongItemName/Sensor_01/Change=9
/TREEX/20_OtherItemName/Sensor_02/MeasuredValue=7.523636
/AW/30_shortName/Sensor_03/ProcessValue=7.507636

我可以将其更改为包含以下内容的新文本文件:

TextFile_new.txt
Sensor_01/Change=9
Sensor_02/MeasuredValue=7.523636
Sensor_03/ProcessValue=7.507636

我做了什么

阅读以下问题:

这个最接近我想要的,但他仍然需要两个文件。

python remove "many" lines from file

这个帮我构建了我的代码。

How do I read a file line-by-line into a list?

这也引起了轩然大波,但我没有多重输入:

https://docs.python.org/3/library/fileinput.html

我使用pycharm和python3编写了下面显示的代码,它对我有用,但我认为它应该比我制作的更容易。

简而言之,它的作用是:删除除最后一个破折号前的姓氏之外的所有内容:' /'以及它背后的内容,并将其转储到一个新的文本文件中(这不是我想要的,我想在可能的情况下替换现有文件)

import os
import sys

# will be user input
directory = r'E:\tempfolder\\'
filename = r'Testfile'

# Temp extention added will be removed later
extention = r'.txt'

# build file location
fullPath = directory+filename+extention
print(fullPath)

# the amount of directories to keep
numOfDirsToKeep = 2

# open selected file
file = open(fullPath, "r")
newFile = []

# read dirs from file and remove everything except the ones to keep.
for line in file:
    splitLine = line.split('/')
    line = splitLine[:-numOfDirsToKeep]
    str1 = '/'.join(line)
    newFile.append(str1)

# close file
file.close()

# insert later : check if file already exists
filename = filename+'_new'
fullPath = directory+filename+extention

# write newFile content to new file
file = open(fullPath, "w")
for items in newFile:
    file.write(items)
    print(items)

我假设这是 WAY 到很多代码来完成此任务。我已经在stackoverflow和google上巡航了很长一段时间了,但据我所知,它不可能在python中做点什么:

# read dirs from file and remove everything except the ones to keep and 
# overwrite line.

# I know this line below is not possible but it indicates what I want.
file = open(fullpath,"rw")

for line in file:
    splitLine = line.split('/')
    line = splitLine[:-numOfDirsToKeep]
    str1 = '/'.join(line)
    file.write(str1)

我想知道

可以从文本文件中重写行而不必: 1.使用Python关闭并重新打开文件 2制作一个新的文本文件 如果是的话,怎么样?

其次: 如果我的问题的答案是" nope",那么我想知道如何使这个过程更有效率,而不是我做到的。它不必专门针对这个例子,替换文本文件中的行对于一般用途最有帮助。

0 个答案:

没有答案