Python Reading a text file - python

I wrote an applescript to generate a text file of all unwatched movies in my itunes library. Here is the code of that script:
tell application "iTunes"
set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
if (count unwatchedEpisodes) > 0 then
set trackNames to {}
repeat with anEpisode in unwatchedEpisodes
set tmp to location of anEpisode as text
set posixtmp to POSIX path of tmp
set end of trackNames to (posixtmp as text)
end repeat
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set unwatchedTVShows to trackNames as text
do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
#display dialog trackNames as text
set AppleScript's text item delimiters to TID
end if
set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
if (count unwatchedEpisodes) > 0 then
set trackNames to {}
repeat with anEpisode in unwatchedEpisodes
set tmp to location of anEpisode as text
set posixtmp to POSIX path of tmp
set end of trackNames to (posixtmp as text)
end repeat
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set unwatchedMovies to trackNames as text
do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
#display dialog trackNames as text
set AppleScript's text item delimiters to TID
end if
end tell
Here is my output file:
/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v
My problem is reading this file. I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".
Anyway, here is my current python code (or at least a snippet of that code):
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies:
line = line.strip()
print line
Here is the output:
/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v
Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file. Any thoughts as to what I'm doing wrong?
Here is the final answer. Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??). Anyway, for future reference, this code:
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
for line in uwmovies:
line = line.replace("\n","")
unwatchedmovies = line.split('\r')
print unwatchedmovies
Gave the output of this list:
['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']
which was exactly what I needed. I list with no "\r" or "\n"'s. Thanks for the help!

Is this your actual code snippet?
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies:
line = line.strip()
print line
This would only print the last line of your file. Note, print line is only indented one tab.

Try calling .read() on the file you open and then split the content up on \n (newline)
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies.read().split('\n'):
line = line.strip()
print line
But this is probably enough for your usecase:
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
umovies_content = umovies.read()
print umovies_content

Try This ( Pythonic Way, UPDATED ) :
import sys
read_lines = [sys.stdout.write(line.rstrip('\n') + "\n") for line in open('1.txt')]
Python 2x
from __future__ import print_function
read_lines = [print(line.rstrip('\n')) for line in open('1.txt')]

Related

File indexing issue in python

for this function, i need to traverse through a file and count each line based on certain signifiers. If that certain signifier is present in the line, i need to add the string as a key to the dictionary and increment its value by one each time its present. I am not outright looking for the answer, I am just lost as to what I have done wrong and where I can proceed from here.
Both of the counter variables and the dictionary are returning empty. I need them to return the values based on what is present on a given file.
file line example:
RT #taylorswift13: Feeling like the luckiest person alive to get to take these brilliant artists out on tour w/ me: #paramore, #beabad00bee & #OwennMusic. I can’t WAIT to see you. It’s been a long time coming 🥰
code:
def top_retweeted(tweets_file_name, num_top_retweeted):
total_tweets = 0
total_retweets = 0
retweets_users = {}
f_read = open(tweets_file_name, "r")
f_write = open(tweets_file_name, "w")
lines = f_read.readlines()
for line in lines:
total_tweets =+1
elements = line.split(":")
for element in elements:
if "RT" in element:
total_retweets =+1
user_name = element.split()
retweet_users[user_name]=+1
print("There were " + str(total_tweets) + " tweets in the file, " + str(total_retweets) + " of which were retweets")
return retweets_user
f_read = open(tweets_file_name, "r")
f_write = open(tweets_file_name, "w")
You're opening the file for reading and then also opening it for writing, which destroys the existing contents.

Replace line in text file using python

This is my program:
filetest = open ("testingfile.txt", "r+")
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for line in filetest:
line = line.rstrip ()
if not ID in line:
continue
else:
templine = '\t'.join(map(str, list))
filetest.write (line.replace(line, templine))
filetest.close ()
I'm trying to replace an entire line containing the ID entered in filetest with templine (templine was a list joined into a string with tabs), and I think the problem with my code is specifically this part filetest.write (line.replace(line, templine)), because when I run the program, the line in the file containing ID doesn't get replaced, but rather templine is added to the end of the line.
For example, if the line in filetest found using the ID entered was "Goodbye\tpython," now it becomes "Goodbye\tpythonHello\tTesting\tFile\t543210" which is not what I want. How do I ensure that line "Goodbye\tpython" is replaced by templine "Hello\tTesting\tFile\t543210", not appended?
As you are reading from the file the file pointer moves as well and it can cause problems. What I would do is first read the file and prepare the "new file" that you want, and then write it into the file, as shown in the code below:
filetest = open ("testingfile.txt", "r")
lines = filetest.readlines()
filetest.close()
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for i in range(len(lines)):
lines[i] = lines[i].rstrip()
if ID not in lines[i]:
continue
else:
templine = '\t'.join(map(str, list))
lines[i] = templine
with open("testingfile.txt", "w") as filetest:
for line in lines:
filetest.write(line + "\n")
I didn't change the logic of the code but be aware that if your file has, for example, a line with the number "56" and a line with the number "5", and you enter the ID "5", then the code will replace both of those lines.

Python Can't load .txt file

photo
This code can't load the log.txt file.
The file is in the temp folder.
Why can't I load it?
This code only displays the text: Search word: ABC.
text = input("Search word: ABC")
with open("C:\Temp\log.txt", encoding = "utf-8") as f:
cnt = 0
for line in f:
l = line.strip().split()
if (l[-1] == text):
print(line.strip())
cnt += 1
if (cnt): print(cnt, "count")
else: print(text, "No data.")
It seems like you need to type the word after running the program. The "ABC" you see is the prompt from the script i.e. it is not entered by you. That's why the program keeps running, waiting for the input and doesn't go further.
Here's your code slightly modified to make it clear.
text = input("Search word: ")
with open("C:\Temp\log.txt", encoding="utf-8") as f:
cnt = 0
for line in f:
if text in line:
print(line.strip())
cnt += 1
if cnt:
print(cnt, "count")
else:
print(text, "No data.")
I guess you understand that your code:
ask the user to input some text
count the occurrences of that text in the file C:\Temp\log.txt, under the conditions:
the text does not contains space
the text is at the end of the line
the text may be followed by one or more spaces
the text must be preceded by one or more spaces
the file cannot have empty lines
Under those conditions, your code should behave nicely. I would recommend to change text = input("Search word: ABC") to text = input("Search word: ") to make it clear that the user need to input some text.
If you still have unexpected results, check if you don't have any character encoding issue (like a terminal default encoding not being utf-8)

Python: How can I search a text file for a string input by the user that contains an integer?

This is an example of what is on the text file that I am searching:
15 - Project `enter code here`Name
APP_IDENTIFIER=ie.example.example
DISPLAY_NAME=Mobile Banking
BUNDLE_VERSION=1.1.1
HEADER_COLOR=#72453h
ANDROID_VERSION_CODE=3
20 - Project Name
APP_IDENTIFIER=ie.exampleTwo.exampleTwp
DISPLAY_NAME=More Mobile Banking
BUNDLE_VERSION=1.2.3
HEADER_COLOR=#23456g
ANDROID_VERSION_CODE=6
If, for example, the user types in 15, I want python to copy the following info:
ie.example.example
Mobile Banking
1.1.1
#72453h
3
because I need to copy it into a different text file.
I get the user to input a project number (in this example the project numbers are 15 & 20) and then I need the program to copy the app_identifier, display_name, bundle_version and android_version of the project relating to the number that the user input.
How do I get python to search the text file for the number input by the user and only take the needed information from the lines directly below that specific project?
I have a whole program written but this is just one section of it.
I don't really have any code yet to find and copy the specific information I need.
Here is code i have to search for the project ID
while True:
CUID = int(input("\nPlease choose an option:\n"))
if (CUID) == 0:
print ("Project one")
break
elif (CUID) == 15:
print ("Project two")
break
elif (CUID) == 89:
print ("Project three")
break
else:
print ("Incorrect input")
The solution thanks to Conor:
projectFile = open("C:/mobileBuildSettings.txt" , "r")
for line in projectFile:
CUID = str(CUID)
if CUID + " - " in line:
appIdentifier = next(projectFile).split("=")[1]
displayName = next(projectFile).split("=")[1]
bundleVersion = next(projectFile).split("=")[1]
next(projectFile)
androidVersionCode = next(projectFile).split("=")[1]
print (appIdentifier, displayName, bundleVersion, androidVersionCode)
break
projectfile = open("projects", "r")
for line in projectfile:
if CUID in line:
appIdentifier = next(projectfile).split("=")[1]
displayName = next(projectfile).split("=")[1]
bundleVersion = next(projectfile).split("=")[1]
next(projectfile)
androidVersionCode = next(projectfile).split("=")[1]
# Do whatever with the 4 values here, call function etc.
break
Then do with appIdentifier, displayName, bundleVersion & androidVersionCode what you will, they will return just the values after the '='.
Although I would recommend against generically searching for an integer, what if the integer is also in the bundle or android version?
There is no reason to list all individual numbers in a long if..else list. You can use a regular expression to check if a line starts with any digit. If it does, check if it matches the number you are looking for, and if it does not, skip the following lines until you reach your blank line separator.
As soon as you have the data you are looking for, you can use a regular expression again to locate the =, or simply use .find:
import re
numberToLookFor = '18'
with open("project.txt") as file:
while True:
line = file.readline()
if not line:
break
line = line.rstrip('\r\n')
if re.match('^'+numberToLookFor+r'\b', line):
while line and line != '':
if line.find('='):
print line[line.find('=')+1:]
line = file.readline().rstrip('\r\n')
else:
while line and line != '':
line = file.readline().rstrip('\r\n')
Here you go:
while True:
CUID = int(input("\nPlease choose an option:\n"))
if (CUID) == 0:
appid = value.split("APP_IDENTIFIER=")[1] # get the value after "APP_IDENTIFIER="
print appid
output >>> ie.example.example
You can apply the same code for all values there, just change the title before "=".
Get the whole line from text then get only the value after "=" with this code for result output.

Split large text file using keyword delimiter

I'm trying to split a large text files into smaller text files by using a word delimiter. I tried searching but I've only seen posts to break apart files after x lines. I'm fairly new to programming but I've given it a start. I want to go through all the lines, and if it starts with hello, it will put all of those lines into one file until it reaches the next hello. The first word in the file is hello. Ultimately, I'm trying to get the text into R, but I think it would be easier if I split it up like this first. Any help is appreciated, thanks.
text_file = open("myfile.txt","r")
lines = text_file.readlines()
print len(lines)
for line in lines :
print line
if line[0:5] == "hello":
If you are finding for a very simple logic, Try this.
text_file = open("myfile.txt","r")
lines = text_file.readlines()
print len(lines)
target = open ("filename.txt", 'a') ## a will append, w will over-write
hello1Found = False
hello2Found = False
for line in lines :
if hello1Found == True :
if line[0:5] == "hello":
hello2Found = True
hello1Found = False
break ## When second hello is found looping/saving to file is stopped
##(though using break is not a good practice here it suffice your simple requirement
else:
print line #write the line to new file
target.write(line)
if hello1Found == False:
if line[0:5] == "hello": ##find first occurrence of hello
hello1Found = True
print line
target.write(line) ##if hello is found for the first time write the
##line/subsequent lines to new file till the occurrence of second hello
I am new to Python. I just finished a Python for Geographic Information Systems class at Northeastern University. This is what I came up with.
import os
import sys
import arcpy
def files():
n = 0
while True:
n += 1
yield open('/output/dir/%d.txt' % n, 'w')
pattern = 'hello'
fs = files()
outfile = next(fs)
filename = r'C:\output\dir\filename.txt'
with open(filename) as infile:
for line in infile:
if pattern not in line:
outfile.write(line)
else:
items = line.split(pattern)
outfile.write
(items[0])
for item in items:
outfile = next(fs)
outfile.write(item)
filename.close();outfile.close();

Categories