I have a text file which consists of many lines of text.
I would like to replace only the first line of a text file using python v3.6 regardless of the contents. I do not need to do a line-by-line search and replace the line accordingly. No duplication with question Search and replace a line in a file in Python
Here is my code;
import fileinput
file = open("test.txt", "r+")
file.seek(0)
file.write("My first line")
file.close()
The code works partially. If the original first line has string longer than "My first line", the excess sub-string still remains. To be clearer, if original line is "XXXXXXXXXXXXXXXXXXXXXXXXX", then the output will be "My first lineXXXXXXXXXXXXXX". I want the output to be only "My first line". Is there a better way to implement the code?
You can use the readlines and writelines to do this.
For example, I created a file called "test.txt" that contains two lines (in Out[3]). After opening the file, I can use f.readlines() to get all lines in a list of string format. Then, the only thing I need to do is to replace the first element of the string to whatever I want, and then write back.
with open("test.txt") as f:
lines = f.readlines()
lines # ['This is the first line.\n', 'This is the second line.\n']
lines[0] = "This is the line that's replaced.\n"
lines # ["This is the line that's replaced.\n", 'This is the second line.\n']
with open("test.txt", "w") as f:
f.writelines(lines)
Reading and writing content to the file is already answered by #Zhang.
I am just giving the answer for efficiency instead of reading all the lines.
Use: shutil.copyfileobj
from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)
Reference
Related
This is my code. What it should do is open the file called example.txt in the same directory and it should only print out the first word of a big list.
with open('example.txt') as file:
line = 'example.txt'
important_info = line.split()
print(important_info[0])
I'm pretty sure I messed up but I don't know how.
I first coded this and it worked
acc = ('info blah bloh blrjejw bfwe tee')
tui = acc.split()
print(tui[0])
In the code I showed above it only prints the first word for one line. But I want something that can do over 100 lines quickly. T think I'm close.
Want to make sure I understand- you want this program to read the first line of a file and print the first word right?
You're on the right track. You're accidentally splitting on the name of the file rather than it's file contents- you're missing the code that reads the contents of the file.
To explain your code:
with open('example.txt') as file:
line = 'example.txt'
important_info = line.split()
print(important_info[0])
( important_info is a list containing just the filename i.e. ['example.txt'] so printing the first element would just be the string example.txt )
Something like this would work (reading the first line, splitting it by whitespace so that it's a list of words and then printing the first word in that list)
f = open("example.txt", "r")
print(f.readline().split()[0])
You need to read the file:
with open('example.txt') as file:
line = file.read()
important_info = line.split()
print(important_info[0])
I have a text file with the following content
this is the first line
this is the second line
this is the third line
this is the fourth line and contains the word fox.
The goal is to write a code that reads the file, extracts the line with
the word fox in it and saves that line to a new text file.Here is the code I have so far
import os
import re
my_absolute_path = os.path.abspath(os.path.dirname(__file__))
with open('textfile', 'r') as helloFile:
for line in helloFile:
if re.findall("fox",line):
print(line.strip())
This code prints the result of the parsed text but thats not really what I want it to do. Instead I would like the code to create a new text file with that line. Is there a way to accomplish this in python?
You can do:
with open('textfile', 'r') as in_file, open('outfile', 'a') as out_file:
for line in in_file:
if 'fox' in line:
out_file.write(line)
Here I've opened the outfile in append (a) mode to accomodate multiple writes. And also used the in (str.__contains__) check for substring existence (Regex is absolutely overkill here).
I want to insert a line into file "original.txt" (the file contains about 200 lines). the line neds to be inserted two lines after a string is found in one of the existing lines. This is my code, I am using a couple of print options that show me that the line is being added to the list, in the spot I need, but the file "original.txt" is not being edited
with open("original.txt", "r+") as file:
lines = file.readlines() # makes file into a list of lines
print(lines) #test
for number, item in enumerate(lines):
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine)
print(lines) #test
break
file.close()
I am turning the lines in the text into a list, then I enumerate the lines as I look for the string, assigning the value of the line to i and adding 2 so that the new line is inserted two lines after, the print() fiction shows the line was added in the correct spot, but the text "original.txt" is not modified
You seem to misunderstand what your code is doing. Lets go line by line
with open("original.txt", "r+") as file: # open a file for reading
lines = file.readlines() # read the contents into a list of lines
print(lines) # print the whole file
for number, item in enumerate(lines): # iterate over lines
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine) # insert lines into the list
print(lines) #test
break # get out of the look
file.close() # not needed, with statement takes care of closing
You are not modifying the file. You read the file into a list of strings and modify the list. To modify the actual file you need to open it for writing and write the list back into it. Something like this at the end of the code might work
with open("modified.txt", "w") as f:
for line in lines: f.write(line)
You never modified the original text. Your codes reads the lines into local memory, one at a time. When you identify your trigger, you count two lines, and then insert the undefined value newLine into your local copy. At no point in your code did you modify the original file.
One way is to close the file and then rewrite it from your final value of lines. Do not modify the file while you're reading it -- it's good that you read it all in and then start processing.
Another way is to write to a new file as you go, then use a system command to replace the original file with your new version.
with open('task3randomtext.txt', 'r') as f:
text = f.readlines()
this is the code I use to take text from a text file and read it into my program but it reads it in as a list an will not let me split it to convert it to a array. Is there any other way or splitting it or reading it in.
If you look at the Python documentation (which you should!) you can see that readlines() returns a list containing every line in the file. To then split each line, you could do something along the lines of:
with open('times.txt') as f:
for line in f.readlines():
print line.split()
Hello I'm making a python program that takes in a file. I want this to be set to a single string. My current code is:
with open('myfile.txt') as f:
title = f.readline().strip();
content = f.readlines();
The text file (simplified) is:
Title of Document
asdfad
adfadadf
adfadaf
adfadfad
I want to strip the title (which my program does) and then make the rest one string. Right now the output is:
['asdfad\n', 'adfadadf\n', ect...]
and I want:
asdfadadfadadf ect...
I am new to python and I have spent some time trying to figure this out but I can't find a solution that works. Any help would be appreciated!
You can do this:
with open('/tmp/test.txt') as f:
title=f.next() # strip title line
data=''.join(line.rstrip() for line in f)
Use list.pop(0) to remove the first line from content.
Then str.join(iterable). You'll also need to strip off the newlines.
content.pop(0)
done = "".join([l.strip() for l in content])
print done
Another option is to read the entire file, then remove the newlines instead of joining together:
with open('somefile') as fin:
next(fin, None) # ignore first line
one_big_string = fin.read().replace('\n', '')
If you want the rest of the file in a single chunk, just call the read() function:
with open('myfile.txt') as f:
title = f.readline().strip()
content = f.read()
This will read the file until EOF is encountered.