python write to file if the file already exist - python

so i wrote a code to split a file(x) into multiple file(y), what if (y) already exist, how do i combine the new file with existing file
here are my current code:
with open('large.dat, encoding='utf-8') as infile, open ('small.dat', 'w', encoding='utf-8') as outfile:
for line in infile:
if '462888' in line:
outfile.write(line)
...
also i want to combine the content from new and existing file without having spaces between them

Open y in a or append mode, if it doesn't exist it will create it, if it does it will add data to it.
with open("y", "a") as file:
file.write("hello world\n")

Related

How to overwrite a csv file ('w' doesn't work well)

I want to overwrite the data in a CSV file when my code runs a second time. I've been using the a+ mode when opening the CSV file and w for writing. However, the new data is getting appended to the existing file instead of overwriting it. How do I overwrite the file?
Here's my code:
with open(r'C:\Users\Desktop\news.csv', 'a+', encoding='utf-8-sig') as file:
writer = csv.writer(file, delimiter=',')
if file.tell()==0:
writer.writerow(['title', 'news', 'img-url'])
if writer.writerow != 0:
writer.writerow([title,news,img])
return writer
Call truncate to clear the file before writing to it.

Appending characters to each line in a txt file with python

I wrote the following python code snippet to append a lower p character to each line of a txt file:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
However, when I execute this python program, it returns nothing but an empty blank:
zhiwei#zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
Can anyone tell me what's wrong with my codes?
Currently, you are only reading each line and not writing to the file. reopen the file in write mode and write your full string to it, like so:
newf=""
with open('helloworld.txt','r') as f:
for line in f:
newf+=line.strip()+"p\n"
f.close()
with open('helloworld.txt','w') as f:
f.write(newf)
f.close()
well, type help(f) in shell, you can get "Character and line based layer over a BufferedIOBase object, buffer."
it's meaning:if you reading first buffer,you can get content, but again. it's empty。
so like this:
with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
newline = ''
for line in f1:
newline+=line.strip()+"p\n"
f2.write(newline)
open(filePath, openMode) takes two arguments, the first one is the path to your file, the second one is the mode it will be opened it. When you use 'r' as second argument, you are actually telling Python to open it as an only reading file.
If you want to write on it, you need to open it in writing mode, using 'w' as second argument. You can find more about how to read/write files in Python in its official documentation.
If you want to read and write at the same time, you have to open the file in both reading and writing modes. You can do this simply by using 'r+' mode.
It seems that your for loop has already read the file to the end, so f.read() return empty string.
If you just need to print the lines in the file, you could move the print into for loop just like print(line). And it is better to move the f.read() before for loop:
f = open("filename", "r")
lines = f.readlines()
for line in lines:
line += "p"
print(line)
f.close()
If you need to modify the file, you need to create another file obj and open it in mode of "w", and use f.write(line) to write the modified lines into the new file.
Besides, it is more better to use with clause in python instead of open(), it is more pythonic.
with open("filename", "r") as f:
lines = f.readlines()
for line in lines:
line += "p"
print(line)
When using with clause, you have no need to close file, this is more simple.

How to read file first line and write from the second

I have a file and I would like to read the first line and write from the second.
with open(file_path, 'r+') as f:
f.readline()
for values in my_array:
f.write("%s=%s" % (str(values[0]), str(values[1])))
Any suggestion?
You can't write on a file while reading it.
Two solutions :
Have a second file where you rewrite your first line and then write the second one :
with open(file_path, 'r+') as f:
line = f.readline()
with open('another_file.txt', 'w') as outfile:
outfile.write(line)
outfile.write(...) # Whatever you want on your second line
Store everything you want to write in memory and then write over your previous file (Which I don't recommend, if something happens midway and your file is stil overwritten, all previous data will be lost).

Store data as numbers in a file in Python

I wrote a program that opens a file and read it line by line and store just the third element of each line. The problem is that, when I write those outputs into a file I need to change them as strings which is not suitable for me due to the fact that I want to do some mathematical operations on the written file later on. FYI, it also is not suitable to store it like this and use int() while reading it.
Can anybody help me with this issue?
with open("/home/test1_to_write", "w") as g:
with open("/home/test1_to_read", 'r') as f:
for line in f:
a=line.split()
number = int(a[3])
g.write(str(number)+'\n')
g.close()
There's no way to tell a text file that 1 is the number one not the letter "1". If you need that, consider storing the whole thing as a list instead using some sort of serial format e.g. JSON:
import json
with open("/home/test1_to_write.json", 'w') as outfile:
with open("/home/test1_to_read", 'r') as infile:
data = [int(line.split()[3]) for line in infile]
json.dump(data, outfile)
You can then load the data with:
with open("/home/test1_to_write.json", "r") as infile:
read_data = json.load(infile)

Store and recall a variable in a text file Python

How would i store the variable x on a specific line (the first)in a text file and recover it as the program opens.
Also how would i store data in a text file on a specific line
You should take a look at the open() built-in.
#To write to a file:
with open("file.txt", "w") as f:
f.write("Data!")
#To read from a file:
with open("file.txt", "r") as f:
print(f.read())
Next time, you should check for duplicates:
easy save/load of data in python, Writing a Top Score to a data file.

Categories

Resources