Удалить первую строку питон

Как удалить первую строку из файла в Python?

@ otha_marks  Вы можете использовать код ниже как пример, который как раз удаляет первую строку из файла в Python:

filename = "test.txt" with open(filename, 'r') as file: lines = file.readlines() if len(lines) > 0: rows = lines[1:] else: rows = [] with open(filename, "w") as file: file.writelines(rows)

Вы можете удалить первую строку из файла, открыв файл в режиме записи, считав первую строку, не записывая ее, и записав остальной контент файла в новый файл. После этого вы можете удалить старый файл и переименовать новый файл так, чтобы он стал старым.

Ниже приведен пример кода, который удаляет первую строку из файла «input.txt» и сохраняет остальной контент в файл «output.txt»:

 1 2 3 4 5 6 7 8 9 10 11 12 13 
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file: # Пропустить первую строку input_file.readline() # Записать все остальные строки в выходной файл for line in input_file: output_file.write(line) # Удалить старый файл os.remove("input.txt") # Переименовать новый файл так, чтобы он стал старым os.rename("output.txt", "input.txt")

Обратите внимание, что этот код использует контекстные менеджеры ( with -блоки) для открытия файлов.

Читайте также:  Colours on html page

Источник

Delete Lines From a File in Python

This article lets you know how to delete specific lines from a file in Python. For example, you want to delete lines #5 and #12.

After reading this article, you’ll learn:

  • How to remove specific lines from a file by line numbers
  • How to delete lines that match or contain the given text/string
  • How to delete the first and last line from a text file.

Table of contents

Delete Lines from a File by Line Numbers

Please follow the below steps to delete specific lines from a text file by line number: –

  1. Open file in a read mode
  2. Read a file. Read all contents from a file into a list using a readlines() method. here each element of a list is a line from the file
  3. Close a file
  4. Again, open the same file in write mode.
  5. Iterate all lines from a list using a for loop and enumerate() function. The enumerate() function adds a counter to an iterable (such as list, string) and returns it in enumerate object. We used the enumerate object with a for loop to access the line number
  6. Use the if condition in each iteration of a loop to check the line number. If it matches the line number to delete, then don’t write that line into the file.
  7. Close a file

The following code shows how to delete lines from a text file by line number in Python. See the attached file used in the example and an image to show the file’s content for reference.

Sample text file

In this example, we are deleting lines 5 and 8.

# list to store file lines lines = [] # read file with open(r"E:\demos\files\sample.txt", 'r') as fp: # read an store all lines into list lines = fp.readlines() # Write file with open(r"E:\demos\files\sample.txt", 'w') as fp: # iterate each line for number, line in enumerate(lines): # delete line 5 and 8. or pass any Nth line you want to remove # note list index starts from 0 if number not in [4, 7]: fp.write(line)

Our code deleted two lines. Here is a current data of a file

First line Second line Third line Fourth line Sixth line Seventh line

The enumerate() function adds a counter to an iterable (such as list, string) and returns it in enumerate object. We used the enumerate object with a for loop to access the line number. The enumerate() doesn’t load the entire list in memory, so this is an efficient solution.

Note: Don’t use del keywords to delete lines from a list and write the same list to file. Because when you delete a line from the list, the item’s index gets changed. So you will no longer be able to delete the correct line.

Using seek() method

The same can be accomplished using the seek() method by changing the pointer position so we don’t need to open a file twice.

  • Open file in the read and write mode ( r+ )
  • Read all lines from a file into the list
  • Move the file pointer to the start of a file using seek() method
  • Truncate the file using the truncate() method
  • Iterate list using loop and enumerate() function
  • In each iteration write the current line to file. Skip those line numbers which you want to remove
with open(r"E:\demos\files\sample.txt", 'r+') as fp: # read an store all lines into list lines = fp.readlines() # move file pointer to the beginning of a file fp.seek(0) # truncate the file fp.truncate() # start writing lines # iterate line and line number for number, line in enumerate(lines): # delete line number 5 and 8 # note: list index start from 0 if number not in [4, 7]: fp.write(line) 

Delete First and Last Line of a File

To selectively delete certain content from the file, we need to copy the file’s contents except for those lines we want to remove and write the remaining lines again to the same file.

Use the below steps to delete the first line from a file.

  • Open file in a read and write mode ( r+ )
  • Read all lines from a file
  • Move file pointer at the start of a file using the seek() method
  • Truncate the file
  • Write all lines from a file except the first line.
with open(r"E:\demos\files\sample.txt", 'r+') as fp: # read an store all lines into list lines = fp.readlines() # move file pointer to the beginning of a file fp.seek(0) # truncate the file fp.truncate() # start writing lines except the first line # lines[1:] from line 2 to last line fp.writelines(lines[1:]) 

Before deleting the first line

First line Second line Third line Fourth line Sixth line Seventh line

After deleting the first line

Second line Third line Fourth line Sixth line Seventh line

To delete the first N lines use list slicing.

# lines[N:] to delete first 5 lines fp.writelines(lines[4:])

If you are reading a file and don’t want to read the first line use the below approach instead of deleting a line from a file.

# read from second line lines = fp.readlines()[1:]

Use the below example to steps to delete the last line from a file

with open(r"E:\demos\files\sample.txt", 'r+') as fp: # read an store all lines into list lines = fp.readlines() # move file pointer to the beginning of a file fp.seek(0) # truncate the file fp.truncate() # start writing lines except the last line # lines[:-1] from line 0 to the second last line fp.writelines(lines[:-1]) 

To delete last N lines use list slicing.

# lines[:-N] to delete last N lines fp.writelines(lines[:-4])

Deleting Lines Matching a text (string)

Assume files contain hundreds of line and you wanted to remove lines which match the given string/text. Let’s see how to remove lines that match the given text (exact match).

  • Read file into a list
  • Open the same file in write mode
  • Iterate a list and write each line into a file except those lines that match the given string.

Example 1: Delete lines that match the given text (exact match)

with open("sample.txt", "r") as fp: lines = fp.readlines() with open("sample.txt", "w") as fp: for line in lines: if line.strip("\n") != "text to delete": fp.write(line)

Also, you can achieve it using the single loop so it will be much faster.

import os with open("sample.txt", "r") as input: with open("temp.txt", "w") as output: # iterate all lines from file for line in input: # if text matches then don't write it if line.strip("\n") != "text to delete": output.write(line) # replace file with original name os.replace('temp.txt', 'sample.txt')

Remove Lines that Contains a Specific Word

We may have to delete lines from a file that contains a particular keyword or tag in some cases. Let’s see the example to remove lines from file that contain a specific string anywhere in the line.

import os with open("sample.txt", "r") as input: with open("temp.txt", "w") as output: # iterate all lines from file for line in input: # if substring contain in a line then don't write it if "word" not in line.strip("\n"): output.write(line) # replace file with original name os.replace('temp.txt', 'sample.txt')

Remove Lines Starting with Specific Word/String

Learn how to remove lines from a file starting with a specific word. In the following example, we will delete lines that begin with the word ‘time‘.

import os with open("sample.txt", "r") as input: with open("temp.txt", "w") as output: # iterate all lines from file for line in input: # if line starts with substring 'time' then don't write it in temp file if not line.strip("\n").startswith('time'): output.write(line) # replace file with original name os.replace('temp.txt', 'sample3.txt')

Delete Specific Text from a Text File

It can also be the case that you wanted to delete a specific string from a file but not the line which contains it. Let’s see the example of the same

import os original_file = "sample3.txt" temp_file = "temp.txt" string_to_delete = ['Emma', 'Kelly'] with open(original_file, "r") as input: with open(temp_file, "w") as output: for line in input: for word in string_to_delete: line = line.replace(word, "") output.write(line) # replace file with original name os.replace('temp.txt', 'sample3.txt') 

Delete all Lines From a File

To delete all the lines in a file and empty the file, we can use the truncate() method on the file object. The truncate() method removes all lines from a file and sets the file pointer to the beginning of the file.

with open("sample3.txt", "r") as fp: fp.truncate()

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Как удалить первую строку из строки?

У меня есть одна большая строка в формате str
«Какой-то текст 1
Какой-то текст 2
Какой-то текст 3
Какой-то текст 4
и тд»
Как удалить первую строку в строке?

Простой 1 комментарий

phaggi

shabelski89

>>> long_str = '''Какой-то текст 1 . Какой-то текст 2 . Какой-то текст 3 . Какой-то текст 4 . и тд''' >>> long_str 'Какой-то текст 1\nКакой-то текст 2\nКакой-то текст 3\nКакой-то текст 4\nи тд' >>> long_str[long_str.find('\n')+1:] 'Какой-то текст 2\nКакой-то текст 3\nКакой-то текст 4\nи тд' >>> print(long_str[long_str.find('\n')+1:]) Какой-то текст 2 Какой-то текст 3 Какой-то текст 4 и тд >>>

phaggi

А ещё можно порубить на кусочки и тогда можно срезом делать от и до нужного.
print(‘\n’.join(long_str.split(‘\n’)[1:3]))

a = '''1111 2222 3333 4444''' del(a.split("\n")[0])

Только делители строк могут быть разные, ‘\n’, ‘\r’, ‘\n\r’, ‘\r\n’, ‘\f’ и другие
И еще — а что, если там одна строка или вообще пустая строка — на «)[1]» будет exception.

devdb,
1. Я в курсе. Мне это расказывать не надо, а вот топикстартеру можете. Он вопрос задавал.
2. Здесь не ресурс по обучению основам языков программирования. Подобные вопросы вообще надо банить.
3. Внимательно прочитайте мой ответ, может поймете, что он не для ТС предназначался.

s=' a b \r\n c d \n e f ' result = '\n'.join(s.splitlines()[1:])

Правда, переносы строк изменятся, если они были не ‘\n’, но зато всё будет работать чётко и по лучшим рецептам Unicode.

import re s=' a b \r\n c d \r e f ' template = r"[^\n\r]*(\r\n|\n\r|[\n\r])?" result = re.sub( template, "", s, count=1)

Здесь после первой строки всё сохранится как было неприкосновенным, даже нестандартные переводы строк (которые не ‘\n’).

Regex хорош тем, что всё можно настраивать как самим хочется. Выше приведён пример для часто встречающихся переводов строк, а вот для всех (надеюсь) вариантов переводов строк, включая даже нуль-символ, который тоже иногда может использоваться для разделения строк (и стандартная splitlines уже с таким не справится, а regex может):

import re s=' a b \u0000 c d \n e f ' template = r"[^\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029\x00]*(\r\n|\n\r|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029\x00])?" result = re.sub( template, "", s, count=1)
import re s=' a b \r\n c d \n e f ' template = r"\r\n|\n\r|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029\x00]" result = "".join( re.split( template, s, maxsplit=1 )[1:] )

Источник

Оцените статью