रिवर्स ऑर्डर में फाइल कैसे पढ़ें?


128

अजगर का उपयोग करके रिवर्स ऑर्डर में फ़ाइल कैसे पढ़ें? मैं अंतिम पंक्ति से पहली पंक्ति की एक फ़ाइल पढ़ना चाहता हूं।


7
क्या आपका मतलब है "इसे रिवर्स ऑर्डर में पढ़ें" या "रिवर्स ऑर्डर में लाइनों की प्रक्रिया करें"? एक अंतर है। पहले के साथ, संभावित रूप से फ़ाइल एक ही समय में सभी मेमोरी में फिट नहीं होगी, इसलिए आप लाइनों को रिवर्स ऑर्डर में संसाधित करना चाहते हैं, लेकिन आप पूरी फ़ाइल को इसमें नहीं पढ़ सकते हैं और इसे रिवर्स कर सकते हैं। दूसरे के साथ, आप बस पूरी फ़ाइल को पढ़ सकते हैं, और उन्हें संसाधित करने से पहले लाइनों की सूची को उल्टा कर सकते हैं। तो यह कौन सा है?
लास वी। कार्लसन


1
मैं यह सलाह देता हूं - कोई स्मृति समस्याएं और तेज: stackoverflow.com/a/260433/1212562
ब्रायन बी

जवाबों:


73
for line in reversed(open("filename").readlines()):
    print line.rstrip()

और पायथन 3 में:

for line in reversed(list(open("filename"))):
    print(line.rstrip())

192
काश, यह काम नहीं करता अगर आप पूरी फ़ाइल को मेमोरी में फिट नहीं कर सकते।
v3232

3
इसके अलावा, जबकि पोस्ट किया गया कोड प्रश्न का उत्तर देता है, हमें उन फाइलों को बंद करने से सावधान रहना चाहिए जो हम खोलते हैं। withबयान आम तौर पर काफी दर्द रहित है।
विलियम

1
@MichaelDavidWatson: पहले मेमोरी में मूल पुनरावृत्‍ति को पढ़े बिना नहीं और फिर रिवर्स में पहले वाले पर एक नया पुनरावृत्ति प्रस्तुत करना।
मैट जॉइनर

3
@MichaelDavidWatson: आप किसी फ़ाइल को रिवर्स में मेमोरी में पढ़े बिना पढ़ सकते हैं, लेकिन यह अनौपचारिक है और काफी सिस्टम कॉल वेस्ट से बचने के लिए बहुत सारे बफर शेंनिगन की आवश्यकता होती है। यह बहुत बुरी तरह से प्रदर्शन करेगा (यद्यपि पूरी मेमोरी को मेमोरी में पढ़ने से बेहतर है यदि फ़ाइल उपलब्ध मेमोरी से अधिक है)।
मैट जॉइनर

1
@William क्षमा करें, मैं फ़ाइल पर पुनरावृत्ति करते हुए "ओपन के साथ" का उपयोग करके उपरोक्त समाधान का उपयोग कैसे करूं और फिर इसे बंद कर दूं?
ब्यूबेकैमोडोर64

146

जनरेटर के रूप में लिखा गया एक सही, कुशल उत्तर।

import os

def reverse_readline(filename, buf_size=8192):
    """A generator that returns the lines of a file in reverse order"""
    with open(filename) as fh:
        segment = None
        offset = 0
        fh.seek(0, os.SEEK_END)
        file_size = remaining_size = fh.tell()
        while remaining_size > 0:
            offset = min(file_size, offset + buf_size)
            fh.seek(file_size - offset)
            buffer = fh.read(min(remaining_size, buf_size))
            remaining_size -= buf_size
            lines = buffer.split('\n')
            # The first line of the buffer is probably not a complete line so
            # we'll save it and append it to the last line of the next buffer
            # we read
            if segment is not None:
                # If the previous chunk starts right from the beginning of line
                # do not concat the segment to the last line of new chunk.
                # Instead, yield the segment first 
                if buffer[-1] != '\n':
                    lines[-1] += segment
                else:
                    yield segment
            segment = lines[0]
            for index in range(len(lines) - 1, 0, -1):
                if lines[index]:
                    yield lines[index]
        # Don't yield None if the file was empty
        if segment is not None:
            yield segment

4
यह पाठ फ़ाइल के लिए python> = 3.2 में काम नहीं करेगा , क्योंकि किसी कारण से फ़ाइल के अंत के सापेक्ष कोई सहायता नहीं मिलती है। फ़ाइल के आकार को सहेजकर fh.seek(0, os.SEEK_END)और fh.seek(-offset, os.SEEK_END)भी बदलकर तय किया जा सकता है fh.seek(file_size - offset)
लेव्सके

9
किए गए संपादन के बाद, यह अजगर 3.5 में पूरी तरह से काम करता है। सवाल का बेहतरीन जवाब।
२०:५५

3
अजगर 2 के लिए इस परिवर्तन को वापस लाएं जहां fh.seek()रिटर्नNone
मारेंगज़

1
देखो कि यह पाठ फ़ाइलों के लिए अपेक्षित के रूप में काम नहीं कर सकता है। ब्लॉक उल्टे क्रम में सही ढंग से प्राप्त करना केवल बाइनरी फ़ाइलों के लिए काम करता है। समस्या यह है कि मल्टी-बाइट एन्कोडिंग (जैसे utf8) के साथ पाठ फ़ाइलों के लिए , seek()और read()विभिन्न आकारों को देखें। शायद यही कारण है कि seek()सापेक्ष के गैर-शून्य पहले तर्क का os.SEEK_ENDसमर्थन नहीं किया जाता है।
norok2

3
सरल: 'aöaö'.encode()है b'a\xc3\xb6a\xc3\xb6'। यदि आप इसे डिस्क में सहेजते हैं और फिर टेक्स्ट मोड में पढ़ते हैं, तो जब आप seek(2)इसे दो बाइट्स से स्थानांतरित करेंगे, तो seek(2); read(1)इसके परिणामस्वरूप त्रुटि होगी UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte, लेकिन यदि आप करते हैं seek(0); read(2); read(1), तो आपको वह मिलेगा जो 'a'आप उम्मीद कर रहे थे, अर्थात: seek()कभी भी एन्कोडिंग नहीं है -अगर, read()अगर आप फ़ाइल को टेक्स्ट मोड में खोलते हैं। अब अगर 'aöaö' * 1000000आपके पास आपके ब्लॉक सही तरीके से संरेखित नहीं होंगे।
norok2

23

इस जैसे किसी और के बारे में क्या राय है:

import os


def readlines_reverse(filename):
    with open(filename) as qfile:
        qfile.seek(0, os.SEEK_END)
        position = qfile.tell()
        line = ''
        while position >= 0:
            qfile.seek(position)
            next_char = qfile.read(1)
            if next_char == "\n":
                yield line[::-1]
                line = ''
            else:
                line += next_char
            position -= 1
        yield line[::-1]


if __name__ == '__main__':
    for qline in readlines_reverse(raw_input()):
        print qline

चूंकि फ़ाइल को रिवर्स ऑर्डर में चरित्र द्वारा चरित्र पढ़ा जाता है, इसलिए यह बहुत बड़ी फ़ाइलों पर भी काम करेगा, जब तक कि व्यक्तिगत लाइनें मेमोरी में फिट हो जाएं।


20

आप अजगर मॉड्यूल का भी उपयोग कर सकते हैं file_read_backwards

इसे स्थापित करने के बाद, pip install file_read_backwards(v1.2.1) के माध्यम से , आप संपूर्ण फ़ाइल को पीछे की ओर (लाइन-वार) मेमोरी कुशल तरीके से पढ़ सकते हैं:

#!/usr/bin/env python2.7

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/path/to/file", encoding="utf-8") as frb:
    for l in frb:
         print l

यह "utf-8", "लैटिन -1" और "अस्की" एनकोडिंग का समर्थन करता है।

पाइथन 3 के लिए सपोर्ट भी उपलब्ध है। आगे के दस्तावेज http://file-read-backwards.readthedocs.io/en/latest/readme.html पर देखे जा सकते हैं


इस समाधान के लिए धन्यवाद। मुझे @srohde द्वारा उपरोक्त समाधान पसंद है (और अपवोट भी किया गया है) क्योंकि इससे मुझे यह समझने में मदद मिली कि यह कैसे किया जाता है, लेकिन एक डेवलपर के रूप में जब मैं कर सकता हूं तो मैं एक मौजूदा मॉड्यूल का उपयोग करना पसंद करता हूं, इसलिए मुझे इस बारे में जानकर खुशी हुई।
जौनिस

1
यह UTF-8 जैसे मल्टीबैट एन्कोडिंग के साथ काम करता है। की तलाश / पढ़ें समाधान नहीं करता है: तलाश () बाइट्स में गिना जाता है, वर्णों में पढ़ा ()।

9
for line in reversed(open("file").readlines()):
    print line.rstrip()

यदि आप लिनक्स पर हैं, तो आप tacकमांड का उपयोग कर सकते हैं ।

$ tac file

2 रेसिपी आप यहां और यहां ActiveState में पा सकते हैं


1
मुझे आश्चर्य है कि अगर उलट () पुनरावृत्ति से पहले पूरे अनुक्रम का उपभोग करता है। डॉक्स का कहना है कि एक __reversed__()विधि की आवश्यकता है, लेकिन python2.5 इसके बिना एक कस्टम वर्ग पर शिकायत नहीं करता है।
मुहुर्त

@ muhuk, शायद इसे किसी तरह से कैश करना है, मुझे संदेह है कि यह रिवर्स ऑर्डर में एक नई सूची बनाता है फिर उस पर एक पुनरावृत्ति देता है
मैट जॉइनर

1
@ मैट: यह हास्यास्पद होगा। यह बस पीछे से सामने की ओर जाती है - लेन (L) -1 पीछे है, 0 सामने है। बाकी की तस्वीर आप देख सकते हैं।
डेविन जीनपिएरे

@ मुहूुक: दृश्यों का सार्थक रूप से उपभोग नहीं किया जाता है (आप पूरे अनुक्रम पर पुनरावृति कर सकते हैं, लेकिन यह बहुत ज्यादा मायने नहीं रखता है)। एक __reversed__विधि भी आवश्यक नहीं है, और इस तरह की चीज होने के लिए उपयोग नहीं किया गया। यदि कोई वस्तु प्रदान करता है __len__और __getitem__यह ठीक काम करेगा (शून्य से कुछ असाधारण मामलों, जैसे कि तानाशाही)।
डेविन जीनपिएरे

@ ड्वेन जीनपिएरे: केवल अगर रीडलाइन () एक वस्तु प्रदान करता है जो प्रदान करता है __reversed__?
मैट जॉइनर

8
import re

def filerev(somefile, buffer=0x20000):
  somefile.seek(0, os.SEEK_END)
  size = somefile.tell()
  lines = ['']
  rem = size % buffer
  pos = max(0, (size // buffer - 1) * buffer)
  while pos >= 0:
    somefile.seek(pos, os.SEEK_SET)
    data = somefile.read(rem + buffer) + lines[0]
    rem = 0
    lines = re.findall('[^\n]*\n?', data)
    ix = len(lines) - 2
    while ix > 0:
      yield lines[ix]
      ix -= 1
    pos -= buffer
  else:
    yield lines[0]

with open(sys.argv[1], 'r') as f:
  for line in filerev(f):
    sys.stdout.write(line)

यह बफ़र से बड़ी फ़ाइलों के लिए गलत आउटपुट का उत्पादन करने के लिए प्रकट होता है। यह सही ढंग से उन पंक्तियों को हैंडल नहीं करेगा, जो आपके द्वारा पढ़े गए बफर-साइज़ चंक्स को समझते हैं। मैंने एक और समान उत्तर (दूसरे समान प्रश्न के लिए) पोस्ट किया।
डेरियस बेकन

@ डैरियस: आह हाँ, मुझे लगता है कि थोड़ा याद किया गया है। अब तय होना चाहिए।
इग्नासियो वाज़क्वेज़-अब्राम

सही लग रहा है। मैं अभी भी अपना कोड पसंद करूंगा क्योंकि यह O (N ^ 2) एक बड़ी फाइल पर काम करता है जो सभी एक लंबी लाइन है। (अन्य प्रश्न के समान उत्तरों में जो मैंने इसका परीक्षण किया, ऐसी फाइलों पर एक गंभीर वास्तविक मंदी का कारण बना।)
डेरियस बेकन

3
अच्छी तरह से प्रश्न में प्रदर्शन का उल्लेख नहीं था, इसलिए मैं नियमित अभिव्यक्ति के प्रदर्शन की गड़बड़ी का सामना नहीं कर सकता: पी
मैट जॉइनर

कुछ और स्पष्टीकरण प्रदर्शन के रूप में उपयोगी होंगे और अगर यह वास्तव में अंतिम पंक्ति कहने की कोशिश कर सकता है और केवल उस टुकड़े को पढ़ सकता है।
user1767754

7

स्वीकृत उत्तर उन बड़ी फ़ाइलों वाले मामलों के लिए काम नहीं करेगा जो मेमोरी में फिट नहीं होंगी (जो कि एक दुर्लभ मामला नहीं है)।

जैसा कि यह दूसरों द्वारा नोट किया गया था, @srohde उत्तर अच्छा लग रहा है, लेकिन इसके अगले मुद्दे हैं:

  • ओपनिंग फ़ाइल बेमानी लगती है, जब हम फ़ाइल ऑब्जेक्ट को पास कर सकते हैं और उपयोगकर्ता को यह तय करने के लिए छोड़ सकते हैं कि किस एन्कोडिंग को पढ़ा जाना चाहिए,
  • यहां तक ​​कि अगर हम फ़ाइल ऑब्जेक्ट को स्वीकार करने के लिए रिफ्लेक्टर करते हैं, तो यह सभी एन्कोडिंग के लिए काम नहीं करेगा: हम utf-8एन्कोडिंग और गैर-एससीआई सामग्री जैसी फ़ाइल चुन सकते हैं

    й

    के buf_sizeबराबर है 1और होगा

    UnicodeDecodeError: 'utf8' codec can't decode byte 0xb9 in position 0: invalid start byte

    बेशक पाठ बड़ा हो सकता है लेकिन buf_size उठाया जा सकता है, इसलिए यह ऊपर की तरह बाधित त्रुटि को जन्म देगा,

  • हम कस्टम लाइन विभाजक निर्दिष्ट नहीं कर सकते,
  • हम लाइन विभाजक रखने का चयन नहीं कर सकते।

इसलिए इन सभी चिंताओं पर विचार करते हुए मैंने अलग-अलग कार्य लिखे हैं:

  • जो बाइट धाराओं के साथ काम करता है,
  • दूसरा जो पाठ धाराओं के साथ काम करता है और अपनी अंतर्निहित बाइट स्ट्रीम को पहले एक को दर्शाता है और परिणामी लाइनों को डिकोड करता है।

सबसे पहले आइए अगले उपयोगिता कार्यों को परिभाषित करें:

ceil_divisionछत के साथ विभाजन बनाने के लिए ( //फर्श के साथ मानक विभाजन के विपरीत , इस धागे में अधिक जानकारी मिल सकती है )

def ceil_division(left_number, right_number):
    """
    Divides given numbers with ceiling.
    """
    return -(-left_number // right_number)

split इसे रखने की क्षमता के साथ दाईं ओर से विभाजक द्वारा स्ट्रिंग को विभाजित करने के लिए:

def split(string, separator, keep_separator):
    """
    Splits given string by given separator.
    """
    parts = string.split(separator)
    if keep_separator:
        *parts, last_part = parts
        parts = [part + separator for part in parts]
        if last_part:
            return parts + [last_part]
    return parts

read_batch_from_end बाइनरी स्ट्रीम के दाईं ओर से बैच पढ़ने के लिए

def read_batch_from_end(byte_stream, size, end_position):
    """
    Reads batch from the end of given byte stream.
    """
    if end_position > size:
        offset = end_position - size
    else:
        offset = 0
        size = end_position
    byte_stream.seek(offset)
    return byte_stream.read(size)

उसके बाद हम रिवर्स ऑर्डर की तरह बाइट स्ट्रीम पढ़ने के लिए फ़ंक्शन को परिभाषित कर सकते हैं

import functools
import itertools
import os
from operator import methodcaller, sub


def reverse_binary_stream(byte_stream, batch_size=None,
                          lines_separator=None,
                          keep_lines_separator=True):
    if lines_separator is None:
        lines_separator = (b'\r', b'\n', b'\r\n')
        lines_splitter = methodcaller(str.splitlines.__name__,
                                      keep_lines_separator)
    else:
        lines_splitter = functools.partial(split,
                                           separator=lines_separator,
                                           keep_separator=keep_lines_separator)
    stream_size = byte_stream.seek(0, os.SEEK_END)
    if batch_size is None:
        batch_size = stream_size or 1
    batches_count = ceil_division(stream_size, batch_size)
    remaining_bytes_indicator = itertools.islice(
            itertools.accumulate(itertools.chain([stream_size],
                                                 itertools.repeat(batch_size)),
                                 sub),
            batches_count)
    try:
        remaining_bytes_count = next(remaining_bytes_indicator)
    except StopIteration:
        return

    def read_batch(position):
        result = read_batch_from_end(byte_stream,
                                     size=batch_size,
                                     end_position=position)
        while result.startswith(lines_separator):
            try:
                position = next(remaining_bytes_indicator)
            except StopIteration:
                break
            result = (read_batch_from_end(byte_stream,
                                          size=batch_size,
                                          end_position=position)
                      + result)
        return result

    batch = read_batch(remaining_bytes_count)
    segment, *lines = lines_splitter(batch)
    yield from reverse(lines)
    for remaining_bytes_count in remaining_bytes_indicator:
        batch = read_batch(remaining_bytes_count)
        lines = lines_splitter(batch)
        if batch.endswith(lines_separator):
            yield segment
        else:
            lines[-1] += segment
        segment, *lines = lines
        yield from reverse(lines)
    yield segment

और अंत में पाठ फ़ाइल को उलटने के लिए एक समारोह की तरह परिभाषित किया जा सकता है:

import codecs


def reverse_file(file, batch_size=None, 
                 lines_separator=None,
                 keep_lines_separator=True):
    encoding = file.encoding
    if lines_separator is not None:
        lines_separator = lines_separator.encode(encoding)
    yield from map(functools.partial(codecs.decode,
                                     encoding=encoding),
                   reverse_binary_stream(
                           file.buffer,
                           batch_size=batch_size,
                           lines_separator=lines_separator,
                           keep_lines_separator=keep_lines_separator))

टेस्ट

तैयारी

मैंने fsutilकमांड का उपयोग करके 4 फाइलें बनाई हैं :

  1. empty.txt कोई सामग्री के साथ, आकार 0MB
  2. छोटे आकार 1MB के साथ
  3. small.txt10 एमबी के आकार के साथ
  4. large.txt 50MB के आकार के साथ

इसके अलावा, मैंने फ़ाइल पथ के बजाय फ़ाइल ऑब्जेक्ट के साथ काम करने के लिए @srohde समाधान को फिर से बनाया है।

टेस्ट स्क्रिप्ट

from timeit import Timer

repeats_count = 7
number = 1
create_setup = ('from collections import deque\n'
                'from __main__ import reverse_file, reverse_readline\n'
                'file = open("{}")').format
srohde_solution = ('with file:\n'
                   '    deque(reverse_readline(file,\n'
                   '                           buf_size=8192),'
                   '          maxlen=0)')
azat_ibrakov_solution = ('with file:\n'
                         '    deque(reverse_file(file,\n'
                         '                       lines_separator="\\n",\n'
                         '                       keep_lines_separator=False,\n'
                         '                       batch_size=8192), maxlen=0)')
print('reversing empty file by "srohde"',
      min(Timer(srohde_solution,
                create_setup('empty.txt')).repeat(repeats_count, number)))
print('reversing empty file by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('empty.txt')).repeat(repeats_count, number)))
print('reversing tiny file (1MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('tiny.txt')).repeat(repeats_count, number)))
print('reversing tiny file (1MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('tiny.txt')).repeat(repeats_count, number)))
print('reversing small file (10MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('small.txt')).repeat(repeats_count, number)))
print('reversing small file (10MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('small.txt')).repeat(repeats_count, number)))
print('reversing large file (50MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('large.txt')).repeat(repeats_count, number)))
print('reversing large file (50MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('large.txt')).repeat(repeats_count, number)))

नोट : मैंने उपयोग किया हैcollections.deque एग्जॉस्ट जनरेटर से क्लास का ।

आउटपुट

विंडोज 10 पर PyPy 3.5 के लिए:

reversing empty file by "srohde" 8.31e-05
reversing empty file by "Azat Ibrakov" 0.00016090000000000028
reversing tiny file (1MB) by "srohde" 0.160081
reversing tiny file (1MB) by "Azat Ibrakov" 0.09594989999999998
reversing small file (10MB) by "srohde" 8.8891863
reversing small file (10MB) by "Azat Ibrakov" 5.323388100000001
reversing large file (50MB) by "srohde" 186.5338368
reversing large file (50MB) by "Azat Ibrakov" 99.07450229999998

विंडोज 10 पर सीपीथॉन 3.5 के लिए:

reversing empty file by "srohde" 3.600000000000001e-05
reversing empty file by "Azat Ibrakov" 4.519999999999958e-05
reversing tiny file (1MB) by "srohde" 0.01965560000000001
reversing tiny file (1MB) by "Azat Ibrakov" 0.019207699999999994
reversing small file (10MB) by "srohde" 3.1341862999999996
reversing small file (10MB) by "Azat Ibrakov" 3.0872588000000007
reversing large file (50MB) by "srohde" 82.01206720000002
reversing large file (50MB) by "Azat Ibrakov" 82.16775059999998

इसलिए जैसा कि हम देख सकते हैं कि यह मूल समाधान की तरह है, लेकिन यह सामान्य है और ऊपर सूचीबद्ध इसके नुकसान से मुक्त है।


विज्ञापन

मैंने इसे पैकेज के0.3.0 संस्करण में जोड़ा है (इसके लिए पायथन 3.5 की आवश्यकता हैlz + की ) जिसमें कई अच्छी तरह से परीक्षण किए गए कार्यात्मक / पुनरावृत्त उपयोगिताओं हैं।

की तरह इस्तेमाल किया जा सकता है

 import io
 from lz.iterating import reverse
 ...
 with open('path/to/file') as file:
     for line in reverse(file, batch_size=io.DEFAULT_BUFFER_SIZE):
         print(line)

यह सभी मानक एन्कोडिंग्स का समर्थन करता है (हो सकता है सिवाय utf-7इसके कि यह मेरे लिए एक रणनीति को परिभाषित करने के लिए एक रणनीति को परिभाषित करने के लिए कठिन है)।


2

यहां आप मेरे कार्यान्वयन को पा सकते हैं, आप "बफर" चर को बदलकर रैम के उपयोग को सीमित कर सकते हैं, एक बग है जो प्रोग्राम शुरुआत में एक खाली लाइन प्रिंट करता है।

और अगर बफ़र बाइट्स से अधिक के लिए कोई नई लाइनें नहीं हैं, तो राम का उपयोग भी बढ़ सकता है, "लीक" चर एक नई रेखा ("\ n") देखने तक बढ़ जाएगा।

यह 16 जीबी फ़ाइलों के लिए भी काम कर रहा है जो कि मेरी कुल मेमोरी से बड़ी है।

import os,sys
buffer = 1024*1024 # 1MB
f = open(sys.argv[1])
f.seek(0, os.SEEK_END)
filesize = f.tell()

division, remainder = divmod(filesize, buffer)
line_leak=''

for chunk_counter in range(1,division + 2):
    if division - chunk_counter < 0:
        f.seek(0, os.SEEK_SET)
        chunk = f.read(remainder)
    elif division - chunk_counter >= 0:
        f.seek(-(buffer*chunk_counter), os.SEEK_END)
        chunk = f.read(buffer)

    chunk_lines_reversed = list(reversed(chunk.split('\n')))
    if line_leak: # add line_leak from previous chunk to beginning
        chunk_lines_reversed[0] += line_leak

    # after reversed, save the leakedline for next chunk iteration
    line_leak = chunk_lines_reversed.pop()

    if chunk_lines_reversed:
        print "\n".join(chunk_lines_reversed)
    # print the last leaked line
    if division - chunk_counter < 0:
        print line_leak

2

उत्तर @srohde के लिए धन्यवाद। इसमें न्यूलाइन कैरेक्टर के लिए 'है' ऑपरेटर है, और मैं 1 प्रतिष्ठा के साथ उत्तर पर टिप्पणी नहीं कर सकता। इसके अलावा, मैं बाहर खुले फ़ाइल का प्रबंधन करना चाहता हूँ क्योंकि यह मुझे luigi कार्यों के लिए अपनी रैलिंग एम्बेड करने में सक्षम बनाता है।

मुझे जो बदलने की आवश्यकता थी, उसका रूप है:

with open(filename) as fp:
    for line in fp:
        #print line,  # contains new line
        print '>{}<'.format(line)

मैं इसे बदलना पसंद करूंगा:

with open(filename) as fp:
    for line in reversed_fp_iter(fp, 4):
        #print line,  # contains new line
        print '>{}<'.format(line)

यहाँ एक संशोधित उत्तर दिया गया है जो एक फ़ाइल संभालना चाहता है और नए अंक रखता है:

def reversed_fp_iter(fp, buf_size=8192):
    """a generator that returns the lines of a file in reverse order
    ref: https://stackoverflow.com/a/23646049/8776239
    """
    segment = None  # holds possible incomplete segment at the beginning of the buffer
    offset = 0
    fp.seek(0, os.SEEK_END)
    file_size = remaining_size = fp.tell()
    while remaining_size > 0:
        offset = min(file_size, offset + buf_size)
        fp.seek(file_size - offset)
        buffer = fp.read(min(remaining_size, buf_size))
        remaining_size -= buf_size
        lines = buffer.splitlines(True)
        # the first line of the buffer is probably not a complete line so
        # we'll save it and append it to the last line of the next buffer
        # we read
        if segment is not None:
            # if the previous chunk starts right from the beginning of line
            # do not concat the segment to the last line of new chunk
            # instead, yield the segment first
            if buffer[-1] == '\n':
                #print 'buffer ends with newline'
                yield segment
            else:
                lines[-1] += segment
                #print 'enlarged last line to >{}<, len {}'.format(lines[-1], len(lines))
        segment = lines[0]
        for index in range(len(lines) - 1, 0, -1):
            if len(lines[index]):
                yield lines[index]
    # Don't yield None if the file was empty
    if segment is not None:
        yield segment

1

एक दूसरी फ़ाइल बनाने के लिए एक सरल कार्य उल्टा (केवल लिनक्स):

import os
def tac(file1, file2):
     print(os.system('tac %s > %s' % (file1,file2)))

कैसे इस्तेमाल करे

tac('ordered.csv', 'reversed.csv')
f = open('reversed.csv')

मुझे लगता है कि लक्ष्य यह था कि इसे पायथन में कैसे किया जाए। इसके अलावा, यह केवल * निक्स सिस्टम पर काम करता है, हालांकि यह उसके लिए एक उत्कृष्ट समाधान है। यह अनिवार्य रूप से शेल उपयोगिताओं को चलाने के लिए एक संकेत के रूप में केवल पायथन का उपयोग कर रहा है।
अलेक्जेंडर हुज़ाग

1
वर्तमान में लिखे गए इस कोड में प्रमुख सुरक्षा बग हैं। क्या होगा अगर आप एक फ़ाइल के साथ बनाई गई रिवर्स करने की कोशिश कर रहे हैंmv mycontent.txt $'hello $(rm -rf $HOME) world.txt' किसी अविश्वसनीय उपयोगकर्ता द्वारा दिए गए आउटपुट फ़ाइल नाम का उपयोग करके या इसी तरह ? यदि आप सुरक्षित रूप से मनमाना फ़ाइल नाम संभालना चाहते हैं, तो यह अधिक सावधानी बरतता है। subprocess.Popen(['tac', file1], stdout=open(file2, 'w'))उदाहरण के लिए, सुरक्षित होगा।
चार्ल्स डफी

मौजूदा कोड भी रिक्त स्थान, वाइल्डकार्ड, और सी के साथ फ़ाइलों को सही ढंग से संभाल नहीं करता है।
चार्ल्स डफी


1

एफ के रूप में खुला ("फ़ाइल नाम"):

    print(f.read()[::-1])

क्या यह पूरी फाइल को पढ़ता है? क्या यह बड़ी फ़ाइलों पर सुरक्षित है? यह करने के लिए एक बहुत ही आसान और यथार्थवादी तरीका लगता है, लेकिन उपरोक्त प्रश्नों के बारे में निश्चित नहीं है .. मैं इस तरह से फ़ाइल को खोजना चाहूंगा (पुनः उपयोग कर) ..
ikwyl6

@ ikwyl6 यह इसके बराबर होना चाहिए list(reversed(f.read()))
एएमसी


0

withफ़ाइलों के साथ काम करते समय हमेशा उपयोग करें क्योंकि यह आपके लिए सब कुछ संभालती है:

with open('filename', 'r') as f:
    for line in reversed(f.readlines()):
        print line

या पायथन 3 में:

with open('filename', 'r') as f:
    for line in reversed(list(f.readlines())):
        print(line)

0

आपको पहले अपनी फाइल को रीड फॉर्मेट में खोलना होगा, उसे एक वैरिएबल में सेव करना होगा, फिर दूसरी फाइल को राइट फॉर्मेट में ओपन करना होगा जहां आप एक [:: - 1] स्लाइस का उपयोग करके वैरिएबल को लिखेंगे या अपग्रेड करेंगे, फाइल को पूरी तरह से उलट देंगे। आप इसे लाइनों की एक सूची में बनाने के लिए रीडलाइन () का भी उपयोग कर सकते हैं, जिसे आप हेरफेर कर सकते हैं

def copy_and_reverse(filename, newfile):
    with open(filename) as file:
        text = file.read()
    with open(newfile, "w") as file2:
        file2.write(text[::-1])

0

कुछ भी करने से पहले अधिकांश उत्तरों को पूरी फ़ाइल पढ़ने की आवश्यकता होती है। यह नमूना अंत से तेजी से बड़े नमूनों को पढ़ता है

मैंने केवल इस उत्तर को लिखते समय मूरत युक्सलेन का उत्तर देखा। यह लगभग वही है, जो मुझे लगता है कि अच्छी बात है। नीचे का नमूना भी \ r से संबंधित है और प्रत्येक चरण में इसके बफ़र को बढ़ाता है। इस कोड को वापस करने के लिए मेरे पास कुछ यूनिट टेस्ट भी हैं ।

def readlines_reversed(f):
    """ Iterate over the lines in a file in reverse. The file must be
    open in 'rb' mode. Yields the lines unencoded (as bytes), including the
    newline character. Produces the same result as readlines, but reversed.
    If this is used to reverse the line in a file twice, the result is
    exactly the same.
    """
    head = b""
    f.seek(0, 2)
    t = f.tell()
    buffersize, maxbuffersize = 64, 4096
    while True:
        if t <= 0:
            break
        # Read next block
        buffersize = min(buffersize * 2, maxbuffersize)
        tprev = t
        t = max(0, t - buffersize)
        f.seek(t)
        lines = f.read(tprev - t).splitlines(True)
        # Align to line breaks
        if not lines[-1].endswith((b"\n", b"\r")):
            lines[-1] += head  # current tail is previous head
        elif head == b"\n" and lines[-1].endswith(b"\r"):
            lines[-1] += head  # Keep \r\n together
        elif head:
            lines.append(head)
        head = lines.pop(0)  # can be '\n' (ok)
        # Iterate over current block in reverse
        for line in reversed(lines):
            yield line
    if head:
        yield head

0

फ़ाइल लाइन को लाइन से पढ़ें और फिर उसे रिवर्स ऑर्डर में एक सूची में जोड़ें।

यहाँ कोड का एक उदाहरण है:

reverse = []
with open("file.txt", "r") as file:
    for line in file:
        line = line.strip()
         reverse[0:0] = line

यह सिर्फ स्वीकृत उत्तर में समाधान के एक अवर संस्करण की तरह लगता है ।
एएमसी


0
def previous_line(self, opened_file):
        opened_file.seek(0, os.SEEK_END)
        position = opened_file.tell()
        buffer = bytearray()
        while position >= 0:
            opened_file.seek(position)
            position -= 1
            new_byte = opened_file.read(1)
            if new_byte == self.NEW_LINE:
                parsed_string = buffer.decode()
                yield parsed_string
                buffer = bytearray()
            elif new_byte == self.EMPTY_BYTE:
                continue
            else:
                new_byte_array = bytearray(new_byte)
                new_byte_array.extend(buffer)
                buffer = new_byte_array
        yield None

उपयोग करने के लिए:

opened_file = open(filepath, "rb")
iterator = self.previous_line(opened_file)
line = next(iterator) #one step
close(opened_file)

-3

मुझे कुछ समय पहले ऐसा करना था और नीचे दिए गए कोड का उपयोग करना था। यह खोल के लिए पाइप। मुझे डर है कि मेरे पास अब पूरी स्क्रिप्ट नहीं है। यदि आप एक यूनिक्स ऑपरेटिंग सिस्टम पर हैं, तो आप "tac" का उपयोग कर सकते हैं, हालाँकि उदाहरण के लिए Mac OSX tac कमांड काम नहीं करता है, टेल -r का उपयोग करें। नीचे दिए गए कोड स्निपेट परीक्षण किस प्लेटफ़ॉर्म पर हैं, और उसके अनुसार कमांड को समायोजित करता है

# We need a command to reverse the line order of the file. On Linux this
# is 'tac', on OSX it is 'tail -r'
# 'tac' is not supported on osx, 'tail -r' is not supported on linux.

if sys.platform == "darwin":
    command += "|tail -r"
elif sys.platform == "linux2":
    command += "|tac"
else:
    raise EnvironmentError('Platform %s not supported' % sys.platform)

पोस्टर से अजगर जवाब मांग रहा है।
मिकमेकाना

खैर, यह एक पायथन जवाब है, हालांकि यह अधूरा लगता है।
DrDee

2
अपने नहीं, नहीं crossplatform, सिस्टम आदेशों का उपयोग = नहीं pythonic
Phyo Arkar Lwin

पोस्टर "अजगर का उपयोग कर" एक जवाब मांग रहा है, जो कोड स्निपेट वास्तव में लिखा गया है। लेकिन मैं मानता हूं कि पोस्ट किए गए अन्य लोगों की तुलना में बहुत अच्छा समाधान नहीं है।
जार्जेन

1
स्निपेट शुद्धता के लिए मूल्यांकन करने के लिए पर्याप्त नहीं है (मंगलाचरण के अन्य भागों को नहीं दिखाया गया है), लेकिन स्ट्रिंग्स में शेल कमांडों को अत्यधिक संदिग्ध और अपने आप में संदिग्ध है - जब तक कि एक महान सौदा नहीं हो जाता है तब तक शेल इंजेक्शन कीड़े होना आसान है देखभाल के लिए।
चार्ल्स डफी
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.