在读取文本文件时,在文件循环中使用for行,如何选择上一行?

时间:2018-02-17 17:44:16

标签: python python-3.x

以下是示例代码

const path = require('path');
const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');

const Sequelize = require('sequelize');
const service = require('feathers-sequelize');

const sequelize = new Sequelize('sandbox', 'sandbox', 'secretpassword', {
  host: 'localhost',
  dialect: 'mysql',

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  operatorsAliases: false
});

const Post = sequelize.define('posts', {
  post_title: Sequelize.STRING,
  post_status: Sequelize.STRING
  
},
{
  timestamps: false,
  underscored: true,
});

// Create an Express compatible Feathers application instance.
const app = express(feathers());

// Turn on JSON parser for REST services
app.use(express.json());
// Turn on URL-encoded parser for REST services
app.use(express.urlencoded({ extended: true }));
// Enable REST services
app.configure(express.rest());
// Enable Socket.io services
app.configure(socketio());


app.use(express.errorHandler());


const myService = {
  find(params) {
    let posts = Post.findAll({
      where: {
        post_status: 'published'
      }
    });

    return Promise.resolve(posts);
  },
  get(id, params) {},
  create(data, params) {},
  update(id, data, params) {},
  patch(id, data, params) {},
  remove(id, params) {},
  setup(app, path) {}
}

app.use('/posts', myService);

// Start the server
const port = 3030;

app.listen(port, () => {
  console.log(`Feathers server listening on port ${port}`);
});

如何在此代码中编写第5行?

1 个答案:

答案 0 :(得分:1)

在每次迭代时保存上一行:

with open('test.txt', 'r') as file:
    previous = None
    find = 'n'
    for line in file:
        if find in line:
            if line != previous:
                print(line)
        previous = line

示例输入:

hello
no
no
hello

输出:

no