Why one thing works and another thing doesn't? [duplicate] - python

This question already has answers here:
Why can't I call read() twice on an open file?
(7 answers)
Closed 5 years ago.
Why does following code1 works and code2 doesn't?
Code1:
#Read from a file
readMe = open('WriteToFile.txt', 'r').read()
print( readMe)
splitMe = readMe.split('\n')
print(splitMe)
Code 2:
#Read from a file
readMe = open('WriteToFile.txt', 'r')
print( readMe.read())
splitMe = readMe.read().split('\n')
print(splitMe)
I am getting the following output for code2:
while I want the output to be like code1 :

Once you call read() to go through a file, the file "pointer" (kinda like cursor) stays at the end of the file, and calling read() again does nothing since you're already at the end (and there's nothing to read). You need to move the pointer to the beginning of the file with file.seek(0).
However, it's better to just read it once to a string and use that:
readMe = open('WriteToFile.txt', 'r')
content = readMe.read()
print( content)
splitMe = content.split('\n')
print(splitMe)
Even better is to use the with statement, which automatically closes the file for you:
with open('WriteToFile.txt', 'r') as file:
content = file.read()
print(content)
lines = content.split('\n')
print(lines)
Although, if your end goal is to just get the lines, you can use readlines():
with open('WriteToFile.txt', 'r') as file:
lines = file.readlines()
print(lines)

Related

open all the text files in a folder [duplicate]

This question already has answers here:
generalize python script to run on all files in a directory
(2 answers)
Closed 8 months ago.
i have this code that takes in a text folder and takes the 25th element in the first line of the file and place it in the 7th. However, this code opens only one text file and writes it to another but what i want that the code reads all the files in the folder and writes them in the same path.
index= 1
with open("3230c237cnc274c.txt", "r") as f:
file = f.readlines()
line = file[index].split(';')
target = line[24]
blank = line[6]
line[6] = target
line[24] = ""
file[index] = ';'.join(line)
with open("aaaaaaaaaaaaaaaa.txt", 'w') as f:
for line in file:
f.write(line)
I like to use the glob module for things like this. See if this helps:
import glob
all_text_files = glob.glob("*.txt")
for text_file in all_text_files:
with open(text_file, "r") as f:
lines = f.readlines()
# do something with the lines...
The syntax "*.txt" indicates all files ending with the .txt extension. This then returns a list of all those filenames. If your files are in a folder somewhere, you can also do "folder/*.txt", and there's a few other nice tricks with glob

What is the difference between read() and readline() in python? [duplicate]

This question already has answers here:
When should I ever use file.read() or file.readlines()?
(5 answers)
Closed 3 years ago.
I am learning file handling in python right now. If i write read() method , it does work same as readline() method . There must be a difference between them and i want to learn that
This question has been answered countless times, and the documentation does a good job of describing the differences, too. But here goes:
If you have a file (test.txt) like so:
first line
second line
third line
Then this code:
with open("test.txt", "r") as file:
line = file.readline()
print(line)
Will produce this output:
first line
That's because readline just reads the next line.
If you use this code instead:
with open("test.txt", "r") as file:
content = file.read()
print(content)
Output:
first line
second line
third line
read() reads the entire contents of the file into a string.
You can also give read() an optional argument, which designates the number of characters to read from the file:
with open("test.txt", "r") as file:
content = file.read(15)
print(content)
Output:
first line
seco
Finally, the third function, which you didn't mention, is readlines, which returns a list of lines (strings):
with open("test.txt", "r") as file:
lines = file.readlines()
print(lines)
Output:
['first line\n', 'second line\n', 'third line\n']
The main difference is that read() will read the whole file at once and then print out the first characters that take up as many bytes as you specify in the parenthesis versus the readline() that will read and print out only the first characters that take up as many bytes as you specify in the parenthesis. You may want to use readline() when you're reading files that are too big for your RAM.

Python: Why do my loops on a certain text file read empty lines although the file is not empty? [duplicate]

This question already has answers here:
Attempting to read open file a second time gets no data
(4 answers)
Using "readlines()" twice in a row [duplicate]
(3 answers)
Closed 4 years ago.
I was trying to learn and experiment with Python today, and I got into trying to open a text file, reading the lines from it, and then writing those lines in a 2nd text file. After that, I tried to load the lines from both files into lists, and print those lists in the console. Here is the experimental code:
f = open('D:\\origFile.txt', 'r')
f2 = open('D:\\copyFile.txt', 'w')
for line in f:
f2.write(line.rstrip() + ' ')
f2.close()
s=""
for linez in f:
s += linez
print (s)
s2=""
f2 = open('D:\\copyFile.txt', 'r+')
reading = f2.readlines()
print (reading)
for linex in f2:
s2 += linex
print (linex)
list1=s.split()
list2=s2.split()
print(list1)
print(list2)
f.close()
f2.close()
The code works as expected only when I remove or comment this part:
f2 = open('D:\\copyFile.txt', 'w')
for line in f:
f2.write(line.rstrip() + ' ')
f2.close()
Although I'm already closing f2 file after writing the contents of f1 to it. So why does it affect the rest of the file operations in the code? And how does it still affect f1? As in, the lists in the end are neither populated by the text from f1 nor f2.
Edit 1: In my question, I already tried to close the second file thinking that it would be the cause of my problem, not the loop itself; while the other question didn't even have a loop to satisfy an answer to my question. Although the answers are somewhat the same, the answer in the other question doesn't show how to use the contents of the file repeatedly without having to reset the iterator using f.seek(0) to be able to use the contents in several loops like in my code above.
You're attempting to loop through the contents of f twice:
for line in f:
for linez in f:
... and you can't do it that way. The second loop will exit immediately, because you already read all of the lines; there are none left to read.
If you want to save the lines of a file and loop through them several times, use something like this:
all_lines = f.readlines()

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.

Replace string within file contents [duplicate]

This question already has answers here:
Replacing instances of a character in a string
(17 answers)
How to search and replace text in a file?
(22 answers)
How to read a large file - line by line?
(11 answers)
Writing a list to a file with Python, with newlines
(26 answers)
Closed 7 months ago.
How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:
I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.
#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
Using pathlib (https://docs.python.org/3/library/pathlib.html)
from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))
If input and output files were different you would use two different variables for read_text and write_text.
If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.
If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.
Something like
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
with open('Stud.txt','r') as f:
newlines = []
for line in f.readlines():
newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
for line in newlines:
f.write(line)
If you are on linux and just want to replace the word dog with catyou can do:
text.txt:
Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Linux Command:
sed -i 's/dog/cat/g' test.txt
Output:
Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...
import re
input = file('C:\full_path\Stud.txt', 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt', 'w')
for each in saved_input:
input.write(each)

Categories