Split at every new instance of string Python - python

I am trying to split some file metadata taken from dropbox at every instance of 'FileMetadata' and write to a text file. It's printing in my console as I need but appending to the text file the new line isn't coming through.
To provide some context to the code I am getting the file meta data and writing it to a file and reading it to then split it.
with open (write_file, 'rt') as read_file:
contents = read_file.read()
data = contents.split('FileMetadata')
print (data)
with open (write_file, 'w') as file1:
file1.write(str(data))

It appears you want a newline for every part that was split by the 'FileMetadata' string.
Instead of your file1.write(str(data)), did you try file1.write("\n".join(data))?

Related

How to create and use a text file in Python?

I need to create a text file in Python to store certain data from a game. I do not want to use numpy, or any external libraries if at all possible.
I need to put some numerical data. Do text files require string data? Also does the data come out of the file as a string?
I know how to create and open a text file, and how to convert string to integer and vice versa, as well as handle CSV file data. I do not know how to handle a text file.
Any ideas on what to do?
To create a file:
file = open("textfile.txt","w+")
This will create a file if it doesn't exist in the directory.
To write inside it:
file.write("This is the content of the file.")
And then you'll have to close the instance with
file.close()
by using the with open command you can create and use it
here is an example
Here w is for writing mode
with open('test.txt','w') as d:
d.write('your text goes here')
You can write to file like this if the file not exists then it will be created
Any ideas on what to do?
Put your data into dict and use built-in json module, example:
import json
data = {'gold': 500, 'name': 'xyzzy'}
# writing
with open('save.json', 'w') as f:
json.dump(data, f)
# reading
with open('save.json', 'r') as f:
data2 = json.load(f)
This create human-readable text file.

i write on a file and read it but it seems when i run again

I want to write a file that says hello guys how are you but each word must be an item of list. Here is my code. It shows nothing when I run it, when I run second time it shows item by item as I want. But when I click text file, it is written two times.
with open('stavanger.txt','r+') as f: # file closes itself with with open as filename command
words = ['hello\n','guys\n','how\n', 'are\n','you\n']
f.writelines(words)
for i in f:
x=i.rstrip().split(',')#turn text file into list and we seperate list items by comma .
print(x)
The problem is that writing to a file uses a buffer. So after the line f.writelines(words) nothing really happened. Only the buffer changed.
In effect, the file still haven't changed and the file pointer is still at the beginning of the file. So the second time you run your code you see the content printed, which leaves the file pointer at the end of the file and only then the buffer is passed to the file and you have the duplicated content.
Simply use mode='w' if you just want to write to a file...
You start reading the file from where the writing stopped. It is better to open the file first for writing, then for reading
Something like this
with open('stavanger.txt', 'w') as f: # file closes itself with with open as filename command
words = ['hello\n', 'guys\n', 'how\n', 'are\n', 'you\n']
f.writelines(words)
with open('stavanger.txt', 'r') as f:
for i in f:
x = i.rstrip().split(',') # turn text file into list and we seperate list items by comma .
print(x)

Python open() doesn't create a file when in w+ mode

I'm creating an application that looks into a website's text and then checks if the input string is in the url of the website's url. The way I'm doing is:
Replace the spaces (' ') in the given string (because url's can't have spaces, duh)
use requests to get the text of the website url
Create a new file and write every string you find in the website in the file.
Read the file line by line and if one line has the string in it, open it in a webbrowser.
I hope I explained it well. Here is my code:
def getGame():
game = gameEntry.get()
gameClean = game.replace(' ', '_')
print(gameClean)
gameCheck1 = requests.get('INSERT LINK HERE')
game2 = gameCheck1.text
with open('Links.txt', 'w+') as f:
f.write(game2)
readLinks = f.readlines()
for link in readLinks:
if game in link:
print(f'Found working link: {link}')
Thanks in advance.
When you write to the file, the file pointer ends up at the end of the file; a subsequent read begins at the end of the file and finds nothing. To fix, call f.seek(0) after the write call to move the file pointer back to the beginning of the file.
Also, just as a side-note, there's no reason to call .readlines(); just delete the readlines line entirely and change the loop to:
for link in f:
and you'll read the lines on demand (instead of creating a whole list of them up front when you only need a line at a time).

Printing a txt file inside python shell

I have an assignment for class that has me transfer txt data from excel and execute in python. But every time I run it, only hex is displayed. I was wondering how to have the data displayed in ascii in the shell. This is the code I have so far. Is it possible to print it out in ascii in the shell?
infile = open("data.txt", 'r')
listName = [line.rstrip() for line in infile]
print (listName)
infile.close()
The reason its not working is because you are opening an Excel file - which is in a special format and is not a plain text file.
You can test this by yourself by opening the file in a text editor like Notepad; and you'll see the contents aren't in text.
To open the file and read its contents in Python you will need to do one of these two things:
Open the file in Excel, then save it as a text file (or a comma separated file CSV). Keep in mind if you do this, then you can only save one sheet at a time.
Use a module like pyexcel which will allow you to read the Excel file correctly in Python.
Just opening the file as plain text (or changing its extension) doesn't convert it.

Adding text and lines to the beginning of a file (Python)

In regards to the related question, I'd like to know how to add text and/or lines to the beginning of a file in Python, as its been suggested that is an easier language for text/file manipulation. So, while I asked the previous, linked, question for C++, can anyone point me to how to do this with Python?
Quote from the linked (related) question:
I'd like to be able to add lines to the beginning of a file.
This program I am writing will take information from a user, and prep
it to write to a file. That file, then, will be a diff that was
already generated, and what is being added to the beginning is
descriptors and tags that make it compatible with Debian's DEP3 Patch
tagging system.
Anyone got any suggestions, or code?
Related: Adding text and lines to the beginning of a file (C++)
There are lot of similar file I/O questions recently..
In short, you need to create a new file
first, write new lines to the file
read lines from old file and write them to file
If you can guarantee each of your new lines added to the beginning is longer than the each of the corresponding original lines at the beginning, you can do it in place:
f = open('file.txt','r+')
lines = f.readlines() # read old content
f.seek(0) # go back to the beginning of the file
f.write(new_content) # write new content at the beginning
for line in lines: # write old content after new
f.write(line)
f.close()
The example above writes all the data in it's entirety after seeking it's position at beginning of file because the contents of file are over-written with new contents.
Otherwise you need to write to a new file
f = open('file.txt','r')
newf = open('newfile.txt','w')
lines = f.readlines() # read old content
newf.write(new_content) # write new content at the beginning
for line in lines: # write old content after new
newf.write(line)
newf.close()
f.close()
Something like this should work:
with open('new.txt', 'w') as new:
with open('prefix.txt') as prefix:
new.write(prefix.read())
with open('old.txt') as old:
new.write(old.read())
If old.txt or prefix.txt contain binary contents, you should add an 'rb' argument to their respective open calls and a 'b' to the flags argument for the first open() call.

Categories