如何打印文件的最新修改部分?

时间:2018-06-13 06:34:11

标签: python python-3.x

我有一个包含以下内容的文件:

--------------------------Thu Jun  7 12:00:01 UTC 2018 -----------------
"Ec2InstanceId":"i-0ec314eafd40e5ad5"
"Ec2InstanceId":"i-0200e84d07ff2c5ed"
"Ec2InstanceId":"i-00a46fde81549e56b"
"Ec2InstanceId":"i-02013e0f353f9aa79"
"Ec2InstanceId":"i-0f5c65a35ef4a7a39"
"Ec2InstanceId":"i-0bddc318b2a5d886b"
"Ec2InstanceId":"i-0e661050aadb9966c"
--------------------------Wed Jun 13 11:26:01 IST 2018 ------------------
"Ec2InstanceId": "i-0ec314eafd40e5ad5",
"Ec2InstanceId": "i-0200e84d07ff2c5ed",
"Ec2InstanceId": "i-00a46fde81549e56b",
"Ec2InstanceId": "i-0cd1f8f7a0c93f7a3",
"Ec2InstanceId": "i-07b291d818a31104b", 
"Ec2InstanceId": "i-003e928cf6faaa441",
"Ec2InstanceId": "i-084383a6edec97d31",
"Ec2InstanceId": "i-0a1ce363d8c8bd773",
"Ec2InstanceId": "i-018771107b26ddfc6",
"Ec2InstanceId": "i-055c6516e3b1fe03d",

现在我想只打印此文件的最新修改部分,在本例中,是文件中的以下部分:

--------------------------Wed Jun 13 11:26:01 IST 2018 ------------------
"Ec2InstanceId": "i-0ec314eafd40e5ad5",
"Ec2InstanceId": "i-0200e84d07ff2c5ed",
"Ec2InstanceId": "i-00a46fde81549e56b",
"Ec2InstanceId": "i-0cd1f8f7a0c93f7a3",
"Ec2InstanceId": "i-07b291d818a31104b", 
"Ec2InstanceId": "i-003e928cf6faaa441",
"Ec2InstanceId": "i-084383a6edec97d31",
"Ec2InstanceId": "i-0a1ce363d8c8bd773",
"Ec2InstanceId": "i-018771107b26ddfc6",
"Ec2InstanceId": "i-055c6516e3b1fe03d",

我是Python的新手,我还没有尝试过任何东西,因为我不知道如何解决这个问题。

3 个答案:

答案 0 :(得分:0)

这是使用datetime和文件的简单迭代的一种方法。

<强>演示:

import datetime
cDate = datetime.datetime.now().strftime ("%a %b %d")

checkString = "--------------------------{0}".format(cDate)
flag = False
res = []
with open(filename, "r") as infile:
    for line in infile:
        if checkString in line:
            flag = True
        if flag:
            res.append(line)

print( "".join(res) )

<强>输出:

--------------------------Wed Jun 13 11:26:01 IST 2018 ------------------
"Ec2InstanceId": "i-0ec314eafd40e5ad5",
"Ec2InstanceId": "i-0200e84d07ff2c5ed",
"Ec2InstanceId": "i-00a46fde81549e56b",
"Ec2InstanceId": "i-0cd1f8f7a0c93f7a3",
"Ec2InstanceId": "i-07b291d818a31104b", 
"Ec2InstanceId": "i-003e928cf6faaa441",
"Ec2InstanceId": "i-084383a6edec97d31",
"Ec2InstanceId": "i-0a1ce363d8c8bd773",
"Ec2InstanceId": "i-018771107b26ddfc6",
"Ec2InstanceId": "i-055c6516e3b1fe03d",

答案 1 :(得分:0)

如果文件不够大并且可以放入你的内存中,你可以简单地反向读取文件并找出包含----------的第一行(从最后)行。由于整个文件内容基本上都是一个长字符串,因此可以使用str.rindex完成,然后从那里读取直到结束:

with open('myfile.txt') as f:
    contents = f.read()
    last_separator_index = contents.rindex('------')
    last_data = contents[last_separator_index:]
    print(last_data.strip('-'))

输出:

"Ec2InstanceId": "i-0ec314eafd40e5ad5",
"Ec2InstanceId": "i-0200e84d07ff2c5ed",
"Ec2InstanceId": "i-00a46fde81549e56b",
"Ec2InstanceId": "i-0cd1f8f7a0c93f7a3",
"Ec2InstanceId": "i-07b291d818a31104b", 
"Ec2InstanceId": "i-003e928cf6faaa441",
"Ec2InstanceId": "i-084383a6edec97d31",
"Ec2InstanceId": "i-0a1ce363d8c8bd773",
"Ec2InstanceId": "i-018771107b26ddfc6",
"Ec2InstanceId": "i-055c6516e3b1fe03d",

如果文件对于内存而言太大,则必须以更复杂和有效的方式从头开始阅读,我会留给您,但您可以从这里开始:Read a file in reverse order using python < / p>

答案 2 :(得分:0)

您想要解决此问题的方法是先读取一个文件,如下所示:

@Component    
@Order(Ordered.HIGHEST_PRECEDENCE)    
public class SimpleCorsFilter implements Filter {

//private final Logger log = LoggerFactory.getLogger(SimpleCorsFilter.class);
    public SimpleCorsFilter() {
        System.out.println("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization, x-auth-token");

        System.out.println("cors filter called");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
         response.setStatus(HttpServletResponse.SC_OK);
        }else {
            chain.doFilter(req, res);
       }
    // chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

这将允许您获取数组中的所有行,其中一行占用一个条目。
为简单起见,我假设您的文件是按顺序编写的,即最新输出将始终位于文件底部。 我会谈到以后不会逆转的情况。

然后您可以使用

简单地颠倒行的顺序
with open("your_file.txt", "r") as f:
    # now you can do stuff with your file, like read the lines:
    lines = f.readlines()

现在,我们只需找到包含日期的行的所有内容(以lines.reverse() 开头:

"-"

如果您希望数据也包含日期行,只需在your_data = [] for line in lines: # the first time we encounter a line starting with "-", we have our most recent date, so we stop. if line[0] == "-": break # otherwise read this line and append it to the data you want. your_data.append(line) 命令之前的行中添加另一个your_data.append(line)

如果您有相反方向的数据(即您最近的日期是文件的顶部),那么您只需跳过break操作即可。 请注意,这也是一种快速但非常黑客的方式,这意味着它的执行速度不会太快。这只会对较大的文件引人注意,但仍应予以考虑。

在处理每条线路方面,这也没有任何作用;所以你必须自己做。如果您需要特殊格式(即numpy数组或类似格式),那里已有大量文献。

这又是完整的代码:

lines.reverse()