[英]Read lines from a txt. file and write all except 6 first lines on another, then flush the first file
I'm trying to create a Python code that reads data from an email, saves it onto a temporary txt. 我正在尝试创建一个Python代码,该代码从电子邮件中读取数据,并将其保存到临时txt中。 file.
文件。 There will be another permanent txt.
将会有另一个永久文本。 file, where the temporary txt.
文件,其中是临时txt。 files contents will be written in a form that skips the first 6 lines.
文件内容将以跳过前6行的形式编写。 During this loop the temporary file gets flushed, so the same data will not be written multiple times.
在此循环期间,将清空临时文件,因此不会多次写入相同的数据。
Here is the code I have worked with: 这是我使用过的代码:
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
save_string = str('C:/Email/file.txt')
myfile = open(save_string, 'a')
myfile.write(str(body)) ## Write to file 2 and then flush this
open ('C:/Email/file.txt','w+') as f:
lines = f.readlines()
open ('C:/Email/newfile.txt','a') as g:
g.writelines(lines[6:])
f.close()
g.close()
myfile.close()# Clear first file
else:
continue
Currently the issue is that it writes the email to the first txt. 当前的问题是它将电子邮件写入第一个txt。 file, but does not update the second txt.
文件,但不会更新第二个txt。 file.
文件。 However, when I run the code again, the previous data gets written to the second txt.
但是,当我再次运行代码时,先前的数据将写入第二个txt。 This is something I don't quite understand why it happens, since the order should be correct.
这是我不太了解为什么会发生的原因,因为顺序应该正确。 Thanks in advance!
提前致谢!
More of the code here: 更多代码在这里:
@view_config(route_name='update-data') def update_view(request): m = imaplib.IMAP4_SSL('imap.gmail.com') m.login('gmail@gmail.com', 'password') m.list() m.select('inbox') result, data = m.uid('search', None, 'UNSEEN') # Only unseen mail i = len(data[0].split()) #space separate string if i == 0: return Response('<h3> Data cannot be updated </h3><h4>No new emails</h4><a href="localhost:8888"> Return to the main page </a> ') for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = m.uid('fetch', latest_email_uid, '(RFC822)') raw_email = email_data[0][1] raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) for part in email_message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload(decode=True) save_string = str('C:/Email/file.txt') myfile = open(save_string, 'a') myfile.write(str(body)) ## Write to file 2 and then flush this open ('C:/Email/file.txt','w+') as f: lines = f.readlines() open ('C:/Email/newfile.txt','a') as g: g.writelines(lines[6:]) f.close() g.close() myfile.close()# Clear first file else: continue return Response('<h3>Data update successful</h3>')
EDIT 编辑
Got it working the way I want with this: 使它按照我想要的方式工作:
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
with open('C:/Email/file.txt', 'a') as myfile: # Opens file.txt and writes the email body
myfile.write(str(body))
with open('C:/Email/file.txt', 'r+') as f: # Opens file.txt again in read mode and reads lines
lines = f.readlines()
with open ('C:/Email/newfile.txt','a') as g: # Writes file.txt contents to newfile.txt, starting from line 6, deletes contents of the first file
g.writelines(lines[6:])
f.truncate(0)
else:
continue
You need to close myfile
before trying to reopen it and you should reopen it in read
mode. 您需要先关闭
myfile
然后再尝试重新打开它,并且应该以read
模式重新打开它。 Try something like this 试试这个
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
save_string = str('C:/Email/file.txt')
myfile = open(save_string, 'a')
myfile.write(str(body)) ## Write to file 2 and then flush this
myfile.close()
open ('C:/Email/file.txt',
'r') as f:
lines = f.readlines()
open ('C:/Email/newfile.txt','a') as g:
g.writelines(lines[6:])
f.close()
g.close()
But it would be better to use with
context manager to open your files, in which case you dont have to worry about closing files 但是最好
with
上下文管理器一起使用来打开文件,在这种情况下,您不必担心关闭文件
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
with open('C:/Email/file.txt', 'a') as myfile:
myfile.write(str(body))
with open('C:/Email/file.txt', 'r') as f:
lines = f.readlines()
with open ('C:/Email/newfile.txt','a') as g:
g.writelines(lines[6:])
You're trying to append to a file that doesn't exist here: 您正在尝试附加到此处不存在的文件:
open ('C:/Email/newfile.txt','a') as g:
g.writelines(lines[6:])
I propose you do something like this: 我建议你做这样的事情:
if os.path.exists('C:/Email/newfile.txt'):
g = open ('C:/Email/newfile.txt','a')
else:
g = open ('C:/Email/newfile.txt','w+')
g.writelines(lines[6:])
Let's take a step back and evaluate the intended goal of your code. 让我们退后一步,评估代码的预期目标。 You want it to basically parse the contents of an email file, and then write contents that are in text/plain format from line 7 and beyond.
您希望它从根本上解析电子邮件文件的内容,然后从第7行开始写入文本/纯格式的内容。 Therefore, we can safely assume that we are dealing with string types.
因此,我们可以放心地假设我们正在处理字符串类型。
Now, your implementation uses a temporary file as a middleman for getting lines 7+. 现在,您的实现使用一个临时文件作为中间人来获取7+行。 However, you can actually skip the usage of the temporary file by parsing the string itself and grabbing lines 7+.
但是,您实际上可以通过解析字符串本身并抓取7+行来跳过临时文件的使用。 Simply split the string by
\\n
, the newline escape sequence, and then rebuild the string from lines 7+. 只需用
\\n
(换行符转义序列)分割字符串,然后从7+行开始重建字符串。
Let's assume the contents of your email part is: 假设您的电子邮件部分的内容为:
>>> mystr = "This is\na message\nwith\nmultiple\nlines\nin the\nstring.\n\nEnd of file"
If I print this, it will show: 如果我打印此文件,它将显示:
>>> print(mystr)
This is
a message
with
multiple
lines
in the
string.
End of file
You can simply split the string now, splitting by \\n
, which returns a list where each element represents a line. 您现在可以简单地分割字符串,用
\\n
分割,这将返回一个列表,其中每个元素代表一行。 From there, you can just grab lines from 7 and beyond, and rejoin the elements with a \\n
. 从那里,您可以仅抓取7以后的直线,然后使用
\\n
重新加入元素。
>>> mystr_split = mystr.split('\n')
>>> mystr_split
['This is', 'a message', 'with', 'multiple', 'lines', 'in the', 'string.', '', 'End of file']
>>> to_write = '\n'.join(mystr_split[6:])
>>> to_write
'string.\n\nEnd of file'
>>> print(to_write)
string.
End of file
So, back to your question, you can simply parse the text/plain content of your email, and just write lines 7+ into one file without using a temporary file. 因此,回到您的问题,您可以简单地解析电子邮件的文本/纯文本内容,只需将7+行写入一个文件,而无需使用临时文件。
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
save_string = r'C:/Email/file.txt'
body_split = body.split('\n')
to_write = '\n'.join(body_split[6:])
with open(save_string, 'w') as f:
f.write(to_write)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.