[python] file & processing

준리·2021년 8월 23일
0

코세라 파이썬
COURSERA
Python Data Structures

  • ch7
    Up to now, we have been working with data that is read from the user or data in constants. But real programs process much larger amounts of data by reading and writing files on the secondary storage on your computer. In this chapter we start to write our first programs that read, scan, and process real data.

7.1 Demonstration

  • Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. You can download the sample data at http://www.py4e.com/code3/words.txt

# Use words.txt as the file name
input("Enter File Name")

fhand = open ("words.txt") #words 파일을 열어
for line in fhand: #라인을 반복해
    line = line.rstrip() #빈 엔터 공간을 지워
    line = line.upper() #모두 대문자로 만들어줘
    print(line) #그리고 출력해

7-2

  • Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
    X-DSPAM-Confidence: 0.8475
    Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
    You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname) #mbox-short.txt를 열어

#평균을 구해야하니까 합과 갯수가 필요해

count = 0 #갯수를 구해
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
        count = count + 1 
        
total = 0 #합계를 구해
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
        line = float(line[21:])
        total = line + total
        
average = total/ count #평균을 구해

print("Average spam confidence:",average)
profile
트렌디 풀스택 개발자

0개의 댓글