Pythons equivalent to PHP's file(fn, FILE_IGNORE_NEW_LINES) [duplicate] - python

This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 9 years ago.
I want to read a file in python and put each new line into an array. I know how to do it in PHP, with the file(fn, FILE_IGNORE_NEW_LINES); function and it's FILE_IGNORE_NEW_LINES parameter, but how do I do it in Python?

When reading a file (line-by-line), usually the new line characters are appended to the end of the line, as you loop through it. If you want to get rid of them?
with open('filename.txt', 'r') as f:
for line in f:
line = line.strip('\n')
#do things with the stripped line!

This is the same as (In Python):
with open("file.txt", "r") as f:
for line in f:
line = line.rstrip("\n")
...

You want this:
with open('filename.txt', 'r') as f:
data = [line.replace('\n', '') for line in f]

Related

How to get just the first word of every line of file using python? [duplicate]

This question already has an answer here:
List the first words per line from a text file in Python
(1 answer)
Closed 7 months ago.
as you can see i'm a newbie and i don't know how to ask this question so i'm going to explain.
i was writing Somali dictionary in text format and i have a lot of words and their meaning, so i want to have those words only not their meaning in another text format file in order to have a list of only vocabulary. Is their a way i can do that. Example "abaabid m.dh eeg abaab². ld ababid. ld abaab¹, abaabis." I have hundred of these words and their meaning and i want to pick only the word "abaabid" and etc. so how can i automate it in python instead of copy pasting manually all day?. Stop saying post the code as text, i don't even know how to write the code and that's why i'm asking this question. This screenshot is the text file showing words with their meaning.
If you just want a script to read the dictionary entries and then write the words into a separate file, try something like this:
def get_words(filename='Somali Dictionary.txt'):
with open(filename, 'r') as f:
lines = [line.split()[0] for line in f.readlines() if line != '\n']
f.close()
return lines
def write_words(lines, filename='Somali Words.txt'):
with open(filename, 'w') as f:
for line in lines:
f.write(line)
f.write('\n')
f.close()
Example usage:
words = get_words()
write_words(words)
Or, alternatively:
if __name__ == '__main__':
words = get_words()
write_words(words)
In order to get the first word of every line follow these steps
f = open('file.txt', 'r')
for line in f:
print(line.split(' ')[0])
or
with open('convert.txt', 'r') as f:
for line in f:
print(line.split(' ')[0])
If it shows you error in console about (UnicodeDecodeError: 'charmap' codec can't decode) you can fix by adding encoding='utf-8'(i'm using .txt file) and my file format is utf-8 and down below is how you are adding in your code
with open('convert.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.split(' ')[0])

How to delete the last 4 characters from every line in a file? - Python [duplicate]

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 2 years ago.
Can anyone give me some advice on creating a loop to cut the last 4 characters from every line within an input file?
I have tried:
myfile = open('delete.txt', 'w+')
myfile.read()
for line in myfile:
line = line[:3]
myfile.close()
The file is formatted like thi:
Awks,1er,xyz,lon,thr,tkj,,^M
Atks,1er,xyz,lon,thr,toj,,^M
Ahks,1er,xyz,lon,thr,taj,,^M
Auks,1er,xaz,lon,thr,tej,,^M
Aqks,1er,xyz,lon,thr,twj,,,^M
Aoks,1er,xaz,lon,thr,twj,,^M
Apks,1er,xwz,lon,thr,trj,,^M
Alks,1er,xuz,lon,thr,toe,,^M
ssks,1er,xoz,lon,thr,toj,,^M
ssks,1er,xnz,lon,thr,tog,,,^M
As some comments said, it's probably safer to open up the input file and write output to a separate file.
Using a with block is handy, because you don't need to handle closing a file; your file is automatically closed at the end of the block.
I'd do something like this:
with open('input.txt', 'r') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line[:-5])
outfile.write('\n')
The line[:-5] will remove the last five characters of each line, which is probably what you want since each line also contains a newline, so it removes the newline and four characters. We outfile.write('\n') because the newline was removed, and we want it back.

How to read each line in a file backwards using Python [duplicate]

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 3 years ago.
I'm trying to read a file (example below), line by line, backwards using Python.
abcd 23ad gh1 n d
gjds 23iu bsddfs ND31 NG
Note: I'm not trying to read the file from the end to the beginning, but I want to read each line starting from the end, i.e d for line 1, and NG for line 2.
I know that
with open (fileName) as f:
for line in f:
reads each line from left to right, I want to read it from right to left.
Try this:
with open(fileName, 'r') as f:
for line in f:
for item in line.split()[::-1]:
print(item)
If your file is not too big, you can read lines in reverse easily
with open(fileName) as f:
for line in reversed(f.readlines()):
# do something
Otherwise, I believe you'd have to use seed.

Manipulating text files: Line deletion if keyword is found [duplicate]

This question already has answers here:
How to delete a specific line in a file?
(17 answers)
Closed 6 years ago.
So I'm attempting to clean up a text file that I have (it is actually a region file which can be loaded into the astronomy fits viewer DS9). I would like to remove/delete the entirety of any line/(s) which contain the keyword "red" in them, for an example:
image;circle(2384.21957861,231.579450647,10.3410929712) # color = red text = {24}
Would anyone know how this could be accomplished within python?
Open an outfile (outfile.txt) for writing, and open your input file (textfile.txt), going line by line through the input file scanning for the keyword (red). If red is not in the line it writes it to the outfile.
with open('outfile.txt', 'w') as o:
with open('textfile.txt') as f:
for line in f.readlines():
if 'red' not in line:
o.write(line)
Make sure the files are within the same directory as the python script.
Based on this answer suggested by #algor, you coul try:
f = open("textfile.txt","r+")
d = f.readlines()
f.seek(0)
for line in d:
if 'red' not in line:
f.write(i)
f.truncate()
f.close()

readlines() method of File Object in Python [duplicate]

This question already has answers here:
Using "readlines()" twice in a row [duplicate]
(3 answers)
Why can't I call read() twice on an open file?
(7 answers)
Closed 7 years ago.
I have a quick question about the readlines() method for file objects in Python.
I have a file (file1.txt) containing the following:
one
two
three
four
five
I know I can use readlines() on this file in the interpreter like so:
>>>f = open('file1.txt', 'r+')
>>>f.readlines()
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
Similarly, I can do this:
>>>f = open('file1.txt', 'r+')
>>>lines = f.readlines()
>>>lines
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
However, it seems like I can only run the readlines() method once:
>>>f = open('file1.txt', 'r+')
>>>f.readlines()
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
>>>lines = f.readlines()
>>>lines
[]
What is going on here? Why does f.readlines() return an empty list the second time I call it?
Thanks.
When you read the file once, the file pointer have moved to the end of the file, you have to call f.seek(0) to move the file pointer back to the start.

Categories